Skip to content

Commit

Permalink
Aded guild list command and made minor changes to other guild commands
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinTrinh1227 committed Oct 20, 2023
1 parent 3658b8b commit 858d9fc
Show file tree
Hide file tree
Showing 4 changed files with 149 additions and 8 deletions.
8 changes: 3 additions & 5 deletions client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
},
"features": {
"filtered_chat": 0,
"auto_gexp": 0,
"inactivity_cmd": 0,
"punishments_cmd": 0
},
Expand All @@ -43,8 +42,8 @@
"welcome": "",
"inactivity_notice": "",
"tickets_transcripts": "",
"leave_messages": "",
"daily_guild_points": ""
"daily_guild_points": "",
"bot_logs": ""
},
"role_ids": {
"guild_member": "",
Expand Down Expand Up @@ -157,7 +156,6 @@ async def print_errors():
else:
pass




client.run(discord_bot_token)

4 changes: 2 additions & 2 deletions commands/guild_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
hypixel_guild_id = data["hypixel_ids"]["guild_id"]


class guildList(commands.Cog):
class guildInfo(commands.Cog):
def __init__(self, client):
self.client = client

Expand Down Expand Up @@ -98,6 +98,6 @@ async def guildinfo(self, ctx):


async def setup(client):
await client.add_cog(guildList(client))
await client.add_cog(guildInfo(client))


132 changes: 132 additions & 0 deletions commands/guild_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import discord
from discord.ext import tasks, commands
from datetime import datetime, timedelta
import json
import discord
import requests
import discord.ui
import os
from dotenv import load_dotenv
import asyncio
import time

# Open the JSON file and read in the data
with open('config.json') as json_file:
data = json.load(json_file)

embed_color = int(data["general"]["embed_color"].strip("#"), 16) #convert hex color to hexadecimal format
hypixel_guild_id = data["hypixel_ids"]["guild_id"]


class guildList(commands.Cog):
def __init__(self, client):
self.client = client
self.guild_id = hypixel_guild_id

@commands.hybrid_command(aliases = ["gl", "guildl"], brief="guildlist", description="Displays list of all guild members", with_app_command=True)
@commands.cooldown(1, 120, commands.BucketType.user) # 2 min cool down.
async def guildlist(self, ctx):


try:

hypixel_api_key = os.getenv("HYPIXEL_API_KEY")
api_link = f'https://api.hypixel.net/guild?key={hypixel_api_key}&id={hypixel_guild_id}'
response = requests.get(api_link)

# Record the start time
start_time = time.time()

if response.status_code == 200:
data = response.json()
members = data['guild']['members']
guild_name = data['guild']['name']

output = ""
total_members = len(members)
total_time = 0
page_size = 25

total_pages = total_members // page_size
if total_members % page_size != 0:
total_pages += 1

await ctx.send(f"Now fetching {guild_name}'s data. Estimated wait time: `{(total_members * 2):.0f}` seconds.")


for idx, member in enumerate(members):
uuid = member["uuid"]
await asyncio.sleep(0.5)
playerdb_url = f'https://playerdb.co/api/player/minecraft/{uuid}'
username_requests = requests.get(playerdb_url)
user_data = username_requests.json()
user_name = user_data["data"]["player"]["username"]


current_time = int(time.time() * 1000)
member_age_ms = current_time - member["joined"]
member_age_days = member_age_ms / (1000 * 60 * 60 * 24)
total_time += member_age_days

if idx % page_size == 0:
if idx > 0:
#print(f"Page {idx // page_size + 1}:")
#print(output) # Print previous 25 players
# Record the end time
end_time = time.time()
# Calculate the elapsed time
elapsed_time = end_time - start_time
#print(f"Elapsed time: {elapsed_time:.2f} seconds")

embed = discord.Embed(
title = f"**📝 | {guild_name} Guild Roster [{idx // page_size}/{total_pages}]**",
description=f"""
You guild has `{total_members}`/`125` members. `{125 - total_members}` Empty slots.
{output}
Days represents time in guild. Page: `{idx // page_size}/{total_pages}`
""",
colour = embed_color
)
#embed.set_thumbnail(url = "{}".format(ctx.guild.icon.url)),
embed.timestamp = datetime.now()
embed.set_footer(text=f"©️ {ctx.guild.name} | {elapsed_time:.0f}s", icon_url = ctx.guild.icon.url)
await ctx.send(embed=embed)
output = ""

output += f"\n**{idx + 1}.** [{user_name}](https://plancke.io/hypixel/player/stats/{uuid}) - `{member_age_days:.2f} days`"
#print(f"\n**{idx + 1}.** [{user_name}](https://plancke.io/hypixel/player/stats/{uuid}) - `{member_age_days:.2f} days`")

# After the loop, print any remaining players
if output:
end_time = time.time()
# Calculate the elapsed time
elapsed_time = end_time - start_time
#print(f"Elapsed time: {elapsed_time:.2f} seconds")
#print(f"Page {idx // page_size + 1}:")
#print(output)
embed = discord.Embed(
title = f"**📝 | {guild_name} Guild Roster [{idx // page_size + 1}/{total_pages}]**",
description=f"""
You guild has `{total_members}`/`125` members. `{125 - total_members}` Empty slots.
{output}
Days represents time in guild. Page: `{idx // page_size + 1}/{total_pages}`
""",
colour = embed_color
)
#embed.set_thumbnail(url = "{}".format(ctx.guild.icon.url)),
embed.timestamp = datetime.now()
embed.set_footer(text=f"©️ {ctx.guild.name} | {elapsed_time:.0f}s", icon_url = ctx.guild.icon.url)
await ctx.send(embed=embed)


except Exception as e:
error_message = str(e)
await ctx.send(f"There was an error: {error_message}. Please double-check your Guild ID and Hypixel API key.")


async def setup(client):
await client.add_cog(guildList(client))


13 changes: 12 additions & 1 deletion commands/guild_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from dotenv import load_dotenv
import asyncio
import time
import pytz

# Open the JSON file and read in the data
with open('config.json') as json_file:
Expand All @@ -27,13 +28,23 @@ def __init__(self, client):
@commands.cooldown(1, 120, commands.BucketType.user) # 2 min cool down.
async def guildpoints(self, ctx):

# Define the Eastern Time Zone
eastern = pytz.timezone('US/Eastern')

# Get the current time in the Eastern Time Zone
current_time = datetime.now(eastern)

# Format the date as "YYYY-MM-DD"
formatted_date = current_time.strftime('%Y-%m-%d')


try:
# Load the "verified_accounts.json" file as a dictionary
with open('verified_accounts.json', 'r') as verified_file:
verified_accounts = json.load(verified_file)

yesterday_date = (datetime.now() - timedelta(days=0)).strftime('%Y-%m-%d') # this means todays date since we subtract 0 days
yesterday_date = formatted_date # this is just todays date EST
# print(yesterday_date)
hypixel_api_key = os.getenv("HYPIXEL_API_KEY")
api_link = f'https://api.hypixel.net/guild?key={hypixel_api_key}&id={hypixel_guild_id}'
response = requests.get(api_link)
Expand Down

0 comments on commit 858d9fc

Please sign in to comment.