Manual import

This commit is contained in:
Tanner Van Teeffelen 2025-04-21 12:40:03 +00:00
parent d87a8b525e
commit 76cde14c7b
5 changed files with 226 additions and 0 deletions

76
bot.py Normal file
View file

@ -0,0 +1,76 @@
#bot.py
##############################
##SETUP##
##############################
#Imports.
import discord, os, json, methods
from discord.ext import commands
from dotenv import load_dotenv
#Load .env file.
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
PREFIX = os.getenv('BOT_PREFIX')
#Sets Discord intents.
intents = discord.Intents.default()
intents.message_content = True
# Create a bot instance with a command prefix of your choice
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
#Load commands to an object named commands_dict.
commands_dict = methods.loadcommands("commands.json")
customcommands_dict = methods.loadcommands("customcommands.json")
##############################
##DEFAULT ACTIONS##
##############################
#Debug message on startup. Not visible to server.
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}!')
#Look for matching commands in JSON file for simple commands.
@bot.event
async def on_message(message):
commands_dict = methods.loadcommands("commands.json")
customcommands_dict = methods.loadcommands("customcommands.json")
if message.author.bot:
return #Ignore any messages from itself.
content = message.content.strip() #Remove the prefix.
if content.startswith(PREFIX):
parts = content[1:].split()
cmd = parts[0]
args = parts[1:]
if cmd in commands_dict:
method_name = commands_dict[cmd]
method = getattr(methods, method_name, None)
if callable(method):
ctx = await bot.get_context(message)
try:
response = await method(ctx, *args)
if response:
await message.channel.send(response)
except TypeError:
await message.channel.send("Invalid number of arguments, or there was an error in the method.")
return
if cmd in customcommands_dict:
response = customcommands_dict[cmd]
response = response.replace("{mention}", message.author.mention)
await message.channel.send(response)
# Run the bot with your token
bot.run(TOKEN)

10
commands.json Normal file
View file

@ -0,0 +1,10 @@
{
"hello": "cmd_hello",
"goodbye": "cmd_goodbye",
"whatareyou": "cmd_whatareyou",
"addpoints": "cmd_addpoints",
"checkpoints": "cmd_checkpoints",
"addcommand": "cmd_addcommand",
"listcommands": "cmd_listcommands",
"roll": "cmd_roll"
}

8
customcommands.json Normal file
View file

@ -0,0 +1,8 @@
{
"!test": "This is a test!",
"tannerisawesome": "He truly is.",
"test2": "This is another test!",
"[": "' t e s t 3 ' , ' t h i s ' , ' i s ' , ' y e t ' , ' a n o t h e r ' , ' t e s t ! ' ]",
"test4": "this is another test!",
"aldan": "Aldan sucks at coding!"
}

128
methods.py Normal file
View file

@ -0,0 +1,128 @@
#methods.py
import os, json, discord, random, math
from dotenv import load_dotenv
#Load .env file.
load_dotenv()
PREFIX = os.getenv('BOT_PREFIX')
#######################################################################################
### COMMANDS - ALL COMMANDS MUST BE ALL LOWERCASE, NO SPACES, WITH A PREFIX OF CMD_ ###
#######################################################################################
async def cmd_hello(ctx):
await ctx.send("Hello, World!")
async def cmd_goodbye(ctx):
await ctx.send("Goodbye!")
async def cmd_whatareyou(ctx):
await ctx.send("An idiot sandwich.")
async def cmd_addpoints(ctx, member: discord.Member = None, number = None):
points_data = loadpoints()
member = member or ctx.author
user_id = str(member.id)
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)
loadpoints(points_data)
await ctx.send(f"{member.mention} now has {points_data[user_id]} points!")
async def cmd_checkpoints(ctx, member: discord.Member = None):
points_data = loadpoints()
member = member or ctx.author # Checks either the member specified, or the sender of the message.
user_id = str(member.id)
points = points_data.get(user_id, 0)
await ctx.send(f"{member.mention} has {points} points.")
async def cmd_addcommand(ctx, command, *message):
response = (" ".join(message))
commands_temp = loadcommands("commands.json")
customcommands_temp = loadcommands("customcommands.json")
if command in commands_temp:
await ctx.send(f"Command '{command}' already exists in base commands! Not overwriting.")
return
if command in customcommands_temp:
await ctx.send(f"Command '{command}' already exists in custom commands! Not overwriting.")
return
customcommands_temp[command] = response
with open("customcommands.json", "w", encoding="utf-8") as file:
json.dump(customcommands_temp, file, indent=4)
await ctx.send(f"Command '{command}' added successfully!")
async def cmd_listcommands(ctx):
try:
commands_dict = loadcommands("commands.json")
customcommands_dict = loadcommands("customcommands.json")
if not commands_dict:
await ctx.send("No commands found in the .JSON file.")
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}\n\n**Available Custom Commands:**\n\n{customcommands_list}\n\n")
except Exception as e:
await ctx.send(f"Error loading commands: {e}")
async def cmd_roll(ctx, inputValue, sign = None, addition = None):
subtotal = 0
total = 0
try:
number, sides = map(int, inputValue.lower().split('d'))
for _ in range(number):
subtotal += rolldie(sides)
if sign and addition:
total = subtotal
addition = int(addition)
if sign == '+':
total = subtotal + addition
elif sign == '-':
total = subtotal - addition
elif sign in ('*', 'X', 'x'):
total = subtotal * addition
elif sign == '/':
total = math.floor(subtotal / addition)
else:
await ctx.send("Invalid mathematical sign passed.")
await ctx.send(f"You rolled a total of {total} ({subtotal} {sign} {addition}).")
else:
await ctx.send(f"You rolled a total of {subtotal}.")
except ValueError as e:
await ctx.send(f"Invalid input - {e}.")
########################################################
### INTERNAL METHODS - ALL METHODS MUST BE LOWERCASE ###
########################################################
def loadcommands(filename):
if not os.path.exists(filename):
with open(filename, "w", encoding="utf-8") as file:
json.dump({}, file) # Create an empty JSON file
with open(filename, "r", encoding="utf-8") as file:
return json.load(file)
def loadpoints():
if not os.path.exists("points.json"):
with open("points.json", "w", encoding="utf-8") as file:
json.dump({}, file) # Create an empty JSON file
with open("points.json", "r", encoding="utf-8") as file:
return json.load(file)
# Saves points to the points.json file.
def savepoints(points_data):
with open("points.json", "w", encoding="utf-8") as file:
json.dump(points_data, file, indent=4)
def rolldie(sides):
return random.randint(1, sides)

4
points.json Normal file
View file

@ -0,0 +1,4 @@
{
"201202009754304513": 18,
"208742496379994113": 3
}