Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bot Changes/Re-Write #4

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.venv/
src/settings/config.json
1 change: 0 additions & 1 deletion TOKEN.txt

This file was deleted.

156 changes: 0 additions & 156 deletions app.py

This file was deleted.

33 changes: 33 additions & 0 deletions linux_mac-start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#!/bin/bash
# Clear terminal
clear
# Load config file
config_file="src/settings/config.json"
token=$(jq -r '.token' "$config_file")
version=$(jq -r '.version' "$config_file")
main_server_id=$(jq -r '.main_server_id' "$config_file")
sync_server_id=$(jq -r '.sync_server_id' "$config_file")

# Check if all required fields are present
if [ -z "$token" ]; then
echo "Missing required config field: token"
exit 1
fi
if [ -z "$version" ]; then
echo "Missing required config field: version"
exit 1
fi
if [ -z "$main_server_id" ]; then
echo "Missing required config field: main_server_id"
exit 1
fi
if [ -z "$sync_server_id" ]; then
echo "Missing required config field: sync_server_id"
exit 1
fi

# Clear terminal
clear

# Start the bot
python3 src/bot.py
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
discord.py==2.4.0
43 changes: 43 additions & 0 deletions src/bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import sys
import os
import json
import discord
from discord.ext import commands
from src.functions.terminalLog import terminal_log
from src.functions.clearTerminal import clear_terminal
from src.functions.syncRoles import sync_roles
from src.functions.loadConfig import load_config
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

async def main():
with open("./src/settings/config.json", "r") as config_file:
CONFIG = json.load(config_file)
TOKEN = CONFIG["token"]
VERSION = CONFIG["version"]
MAIN_SERVER_ID = CONFIG["main_server_id"]
SYNC_SERVER_ID = CONFIG["sync_server_id"]
ROLE_ID_MAP = {int(k): int(v) for k, v in CONFIG["role_id_map"].items()}

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix="s.", intents=intents)

@client.event
async def on_ready():
await clear_terminal()
await client.change_presence(status=discord.Status.online)
await terminal_log("BOT", f"{client.user.name} version {VERSION} loaded.")
await terminal_log("BOT", f"{client.user.name} ({client.user.id}) is now online.")

@client.event
async def on_member_update(before, after):
if before.roles != after.roles and before.guild.id == MAIN_SERVER_ID:
await terminal_log("BOT", f"Synchronized roles for {before.name} as they updated in the Main Server.")
await sync_roles(before.guild, client.get_guild(SYNC_SERVER_ID), before.id, ROLE_ID_MAP)

await client.start(TOKEN)

if __name__ == "__main__":
import asyncio
asyncio.run(main())
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
37 changes: 37 additions & 0 deletions src/functions/clearTerminal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import os
from src.functions.terminalLog import terminal_log

async def clear_terminal():
"""
Clears the terminal screen.

This function attempts to clear the terminal screen using the appropriate command
for the operating system. It logs the success or failure of the operation and ensures
that a completion message is logged regardless of the outcome.

Logs:
SYSTEM: Terminal cleared.
ERROR: Failed to clear terminal: <exception message>
SYSTEM: clear_terminal function executed.

Returns:
None

Raises:
Exception: If an error occurs while attempting to clear the terminal.

The function performs the following steps:
1. Attempts to clear the terminal screen using 'cls' for Windows and 'clear' for Unix-based systems.
2. Logs a message indicating that the terminal has been cleared.
3. If an error occurs during the clearing process, logs an error message with the exception details.
4. Logs a message indicating that the function execution is completed, regardless of success or failure.
"""
try:
os.system('cls' if os.name == 'nt' else 'clear')
await terminal_log("SYSTEM", "Terminal cleared.")
except Exception as e:
await terminal_log("ERROR", f"Failed to clear terminal: {e}")
finally:
await terminal_log("SYSTEM", "clear_terminal function executed.")

__all__ = ['clear_terminal']
76 changes: 76 additions & 0 deletions src/functions/syncRoles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import discord
from src.functions.terminalLog import terminal_log

__all__ = ['sync_roles']

async def sync_roles(main_server, sync_server, user_id, role_id_map):
"""
Synchronizes roles for a user between the main server and the sync server.
This function retrieves the user from both the main server and the sync server,
removes any roles in the sync server that are mapped in the role_id_map, and then
adds roles to the user in the sync server based on their roles in the main server.
Args:
main_server (discord.Guild): The main server object where the user's roles are sourced.
sync_server (discord.Guild): The sync server object where the user's roles are synchronized.
user_id (int): The ID of the user whose roles are being synchronized.
role_id_map (dict): A dictionary mapping role IDs from the main server to the sync server.
Returns:
None
Logs:
"DEBUG": If the user is not found in either the main server or the sync server.
"BOT": When roles are successfully cleared or added in the sync server.
"ERROR": If there are missing permissions to remove or add roles, or if any other error occurs during synchronization.
"DEBUG": When the role synchronization process is completed.
Raises:
Exception: If any error occurs during the role synchronization process.
The function performs the following steps:
1. Retrieves the user from both the main server and the sync server.
2. Logs a debug message if the user is not found in either server.
3. Identifies roles in the sync server that need to be removed based on the role_id_map.
4. Attempts to remove the identified roles from the user in the sync server.
5. Logs a message if roles are successfully removed or if there are missing permissions.
6. If the user is found in the main server, retrieves their roles.
7. Maps the user's roles from the main server to the sync server using the role_id_map.
8. Attempts to add the mapped roles to the user in the sync server.
9. Logs a message if roles are successfully added or if there are missing permissions.
10. Logs a debug message when the role synchronization process is completed.
"""
try:
main_member = main_server.get_member(user_id)
sync_member = sync_server.get_member(user_id)

if main_member is None:
await terminal_log("DEBUG", f"User with ID {user_id} not found in Main Server.")
if sync_member is None:
await terminal_log("DEBUG", f"User with ID {user_id} not found in Sync Server.")
return

sync_roles_to_remove = [role for role in sync_member.roles if role.id in role_id_map.values()]

if sync_roles_to_remove:
try:
await sync_member.remove_roles(*sync_roles_to_remove, reason="Removing sync roles.")
await terminal_log("BOT", f"Cleared sync roles for {sync_member.name} in the Sync Server.")
except discord.errors.Forbidden:
await terminal_log("ERROR", f"Missing permissions to remove roles from {sync_member.name} in the Sync Server.")

if main_member is None:
return

main_user_roles = [role.id for role in main_member.roles]
sync_user_roles = [role.id for role in sync_member.roles]

for role_id in main_user_roles:
sync_role_id = role_id_map.get(role_id)
if sync_role_id:
sync_role = sync_server.get_role(sync_role_id)
if sync_role:
try:
await sync_member.add_roles(sync_role, reason="Syncing roles from the main server.")
await terminal_log("BOT", f"Gave {sync_member.name} the role {sync_role.name} in the Sync Server.")
except discord.errors.Forbidden:
await terminal_log("ERROR", f"Missing permissions to add roles to {sync_member.name} in the Sync Server.")
except Exception as e:
await terminal_log("ERROR", f"An error occurred during role synchronization: {e}")
finally:
await terminal_log("DEBUG", "Role synchronization process completed.")
Loading