Files
.gitignore
bot.py
requirements.txt
Code
3 700
bot.py
import discord
from discord import app_commands
from discord.ext import commands
import os
from dotenv import load_dotenv
import json
from datetime import datetime, timedelta
from typing import Optional
import asyncio
load_dotenv()
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
BRAND_COLOR = 0x0D4F4F
ACCENT_COLOR = 0xC0C0C0
SUCCESS_COLOR = 0x2ECC71
ERROR_COLOR = 0xE74C3C
DATA_FILE = 'data.json'
def load_data():
try:
with open(DATA_FILE, 'r') as f:
return json.load(f)
except FileNotFoundError:
return {'users': {}, 'pending_loans': []}
def save_data(data):
with open(DATA_FILE, 'w') as f:
json.dump(data, f, indent=4)
def get_user_account(user_id: str):
data = load_data()
if user_id not in data['users']:
data['users'][user_id] = {
'balance': 1000.00,
'loans': [],
'plan': None,
'transaction_history': []
}
save_data(data)
return data['users'][user_id]
def update_user_account(user_id: str, account_data):
data = load_data()
data['users'][user_id] = account_data
save_data(data)
def create_brand_embed(title: str, description: str = None, color: int = BRAND_COLOR):
embed = discord.Embed(
title=title,
description=description,
color=color,
timestamp=datetime.utcnow()
)
embed.set_footer(text="Moat & Castle Credit Union", icon_url="https://i.imgur.com/placeholder.png")
return embed
class LoanRequestView(discord.ui.View):
def __init__(self, request_id: int, user_id: str, amount: float, reason: str, interest_rate: float, monthly_payment: float):
super().__init__(timeout=None)
self.request_id = request_id
self.user_id = user_id
self.amount = amount
self.reason = reason
self.interest_rate = interest_rate
self.monthly_payment = monthly_payment
@discord.ui.button(label="Approve", style=discord.ButtonStyle.success, emoji="โ
")
async def approve_button(self, interaction: discord.Interaction, button: discord.ui.Button):
# Check if user has staff role
if not any(role.name.lower() == "staff" for role in interaction.user.roles):
await interaction.response.send_message("โ Only staff members can approve loans!", ephemeral=True)
return
data = load_data()
# Remove from pending loans
data['pending_loans'] = [req for req in data.get('pending_loans', []) if req['request_id'] != self.request_id]
# Add loan to user's account
account = get_user_account(self.user_id)
loan = {
'amount': self.amount,
'remaining': self.amount,
'interest_rate': self.interest_rate,
'monthly_payment': self.monthly_payment,
'date_issued': datetime.now().strftime('%Y-%m-%d'),
'reason': self.reason,
'approved_by': str(interaction.user)
}
account['loans'].append(loan)
account['balance'] += self.amount
update_user_account(self.user_id, account)
save_data(data)
# Disable buttons
for item in self.children:
item.disabled = True
# Update the message
approval_embed = create_brand_embed(
title="โ
Loan Request APPROVED",
description=f"This loan has been approved by {interaction.user.mention}",
color=SUCCESS_COLOR
)
approval_embed.add_field(name="๐ค Applicant", value=f"<@{self.user_id}>", inline=True)
approval_embed.add_field(name="๐ต Amount", value=f"${self.amount:,.2f}", inline=True)
approval_embed.add_field(name="๐ Interest Rate", value=f"{self.interest_rate}%", inline=True)
approval_embed.add_field(name="๐
Monthly Payment", value=f"${self.monthly_payment:,.2f}", inline=True)
approval_embed.add_field(name="๐ Reason", value=self.reason, inline=False)
approval_embed.add_field(name="โ
Approved By", value=interaction.user.mention, inline=True)
approval_embed.add_field(name="โฐ Approved At", value=f"<t:{int(datetime.now().timestamp())}:F>", inline=True)
await interaction.response.edit_message(embed=approval_embed, view=self)
# Notify the user
try:
user = await bot.fetch_user(int(self.user_id))
user_embed = create_brand_embed(
title="๐ Loan Approved!",
description=f"Your loan request has been approved by staff!",
color=SUCCESS_COLOR
)
user_embed.add_field(name="๐ต Loan Amount", value=f"${self.amount:,.2f}", inline=True)
user_embed.add_field(name="๐ Interest Rate", value=f"{self.interest_rate}%", inline=True)
user_embed.add_field(name="๐
Monthly Payment", value=f"${self.monthly_payment:,.2f}", inline=True)
user_embed.add_field(name="๐ฐ New Balance", value=f"${account['balance']:,.2f}", inline=False)
user_embed.add_field(name="๐ Note", value="The funds have been deposited into your account. Use `/balance` to view your account.", inline=False)
await user.send(embed=user_embed)
except:
pass
@discord.ui.button(label="Reject", style=discord.ButtonStyle.danger, emoji="โ")
async def reject_button(self, interaction: discord.Interaction, button: discord.ui.Button):
# Check if user has staff role
if not any(role.name.lower() == "staff" for role in interaction.user.roles):
await interaction.response.send_message("โ Only staff members can reject loans!", ephemeral=True)
return
# Show modal to get rejection reason
modal = RejectReasonModal(self)
await interaction.response.send_modal(modal)
class RejectReasonModal(discord.ui.Modal, title="Reject Loan Request"):
def __init__(self, view: LoanRequestView):
super().__init__()
self.view = view
reason = discord.ui.TextInput(
label="Reason for Rejection",
placeholder="Enter the reason why this loan is being rejected...",
style=discord.TextStyle.paragraph,
required=True,
max_length=500
)
async def on_submit(self, interaction: discord.Interaction):
data = load_data()
# Remove from pending loans
data['pending_loans'] = [req for req in data.get('pending_loans', []) if req['request_id'] != self.view.request_id]
save_data(data)
# Disable buttons
for item in self.view.children:
item.disabled = True
# Update the message
rejection_embed = create_brand_embed(
title="โ Loan Request REJECTED",
description=f"This loan has been rejected by {interaction.user.mention}",
color=ERROR_COLOR
)
rejection_embed.add_field(name="๐ค Applicant", value=f"<@{self.view.user_id}>", inline=True)
rejection_embed.add_field(name="๐ต Requested Amount", value=f"${self.view.amount:,.2f}", inline=True)
rejection_embed.add_field(name="๐ Original Reason", value=self.view.reason, inline=False)
rejection_embed.add_field(name="โ Rejection Reason", value=self.reason.value, inline=False)
rejection_embed.add_field(name="โ Rejected By", value=interaction.user.mention, inline=True)
rejection_embed.add_field(name="โฐ Rejected At", value=f"<t:{int(datetime.now().timestamp())}:F>", inline=True)
await interaction.response.edit_message(embed=rejection_embed, view=self.view)
# Notify the user
try:
user = await bot.fetch_user(int(self.view.user_id))
user_embed = create_brand_embed(
title="โ Loan Request Rejected",
description=f"Your loan request has been rejected by staff.",
color=ERROR_COLOR