Skip to content

Commit

Permalink
Use configure.py in install scripts config step.
Browse files Browse the repository at this point in the history
Add token checking to configure.py
  • Loading branch information
itsTheFae committed Dec 23, 2024
1 parent 53b1ab7 commit 42850a1
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 181 deletions.
53 changes: 53 additions & 0 deletions configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@
MODE_EDIT_OPTION = 3
MODE_EDIT_FIELD = 3

# Status codes for token verification.
VERIFY_SUCCESS = 0
VERIFY_FAILED_LIBRARY = 1
VERIFY_FAILED_API = 2
VERIFY_FAILED_MGR = 3


class ServerData:
"""
Expand Down Expand Up @@ -179,6 +185,7 @@ def __init__(self, stdscr: curses.window) -> None:
self.edited_opts: Set[ConfigOption] = set()
self.edited_perms: Set[ConfigOption] = set()
self.edited_aliases: Set[str] = set()
self.token_status: int = 0

# store valid commands from musicbot.
self.top_commands: Set[str] = set()
Expand Down Expand Up @@ -250,6 +257,35 @@ def _get_servers(self) -> List[ServerData]:

return list(srvs.values())

def _verify_bot_token(self) -> int:
"""Create a discord client which immediately closes, to test tokens."""
try:
import discord
except Exception: # pylint: disable=broad-exception-caught
return VERIFY_FAILED_LIBRARY

if self.mgr_opts is None:
return VERIFY_FAILED_MGR

try:
client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_ready() -> None:
await client.close()

@client.event
async def on_error() -> None:
await client.close()

client.run(
self.mgr_opts._login_token, # pylint: disable=protected-access
log_handler=None,
)
except Exception: # pylint: disable=broad-exception-caught
return VERIFY_FAILED_API
return VERIFY_SUCCESS

def get_text_input(
self, lines: int, cols: int, y: int, x: int, value: str = ""
) -> str:
Expand Down Expand Up @@ -692,6 +728,21 @@ def reload_callback() -> None:
"This option is missing from your INI file.",
curses.color_pair(12),
)
if selected_opt.option == "Token" and self.token_status:
if self.token_status == VERIFY_FAILED_API:
self.win.addstr(
5,
33 + len(lbl_current),
"ERROR: Token failed to log in!",
curses.color_pair(12),
)
elif self.token_status == VERIFY_FAILED_LIBRARY:
self.win.addstr(
5,
33 + len(lbl_current),
f"WARNING: Cannot verify, internal error {self.token_status}",
curses.color_pair(12),
)
cflags = 0
if len(cval) >= 199:
cflags = curses.color_pair(12)
Expand Down Expand Up @@ -739,6 +790,8 @@ def reload_callback() -> None:
)
else:
self.edited_opts.add(selected_opt)
if selected_opt.option == "Token":
self.token_status = self._verify_bot_token()

self.win.refresh()

Expand Down
69 changes: 3 additions & 66 deletions install.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -266,73 +266,10 @@ if($iagree -ne "Y" -and $iagree -ne "y")

Copy-Item ".\config\example_options.ini" -Destination ".\config\options.ini"

# GET AND VERIFY TOKEN
""
"Please enter your bot token. This can be found in your discordapp developer page."
$token = Read-Host "Enter Token" -AsSecureString
$token_plain = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($token))
$header = @{
"Authorization" = "Bot $token_plain"
"Content-Type" = "application/json"
}
$result = Invoke-WebRequest -Headers $header -Method "GET" -Uri "$DEFAULT_URL_BASE/users/@me"
$result_code = $result.StatusCode
$result_content = $result.Content
if (!($result_code -eq 200))
{
"Error getting user profile, is the token correct? ($result_code $result_content)"
""
"You can finish the configuration manually by editing the options.ini file in the config folder."
Return
}
$result_object = ConvertFrom-Json -InputObject $result_content
# Cause whoever wrote ConvertFrom-Json cmdlet was insane and use some strange data type instead
$result_table = @{}
$result_object.PsObject.Properties | ForEach-Object{
$result_table[$_.Name] = $_.Value
}
$result_table += @{"token" = $token_plain}
$config = (Get-Content -Path ".\config\options.ini") -creplace "bot_token", $token_plain

# GET PREFIX
$cprefix = Read-Host "Would you like to change the command prefix? [N/y]: "
if($cprefix -eq "Y" -or $cprefix -eq "y")
{
"Please enter the prefix you'd like for your bot."
$prefix = Read-Host "This is what comes before all commands. The default is [!] "
$config = $config -creplace "CommandPrefix = !", "CommandPrefix = $prefix"
}
else
{
"Using default prefix [!]"
}

# GET OWNER
$cowner = Read-Host "Would you like to automatically get the owner ID from the OAuth application? [Y/n]: "
if($cowner -eq "N" -or $cowner -eq "n")
{
$owner = Read-Host "Please enter the owner ID. "
$config = $config -creplace "OwnerID = auto", "OwnerID = $owner"
}
else
{
"Getting owner ID from OAuth application..."
}

# GET AP
$cap = Read-Host "Would you like to enable the autoplaylist? [Y/n] "
if($cap -eq "N" -or $cap -eq "n")
{
$config = $config -creplace "UseAutoPlaylist = yes", "UseAutoPlaylist = no"
"Autoplaylist disabled"
}
else
{
"Autoplaylist enabled"
}
"Copied example_options.ini to options.ini"
"Starting configure.py configuration tool..."

"Saving your config..."
Set-Content -Path ".\config\options.ini" -Value $config
Invoke-Expression "$PYTHON configure.py"

"You can use run.bat to run the bot."
"Restart your command prompt first!"
Expand Down
120 changes: 5 additions & 115 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,15 @@ DEBUG=0


#----------------------------------------------Constants----------------------------------------------#
DEFAULT_URL_BASE="https://discordapp.com/api"
# Suported versions of python using only major.minor format
PySupported=("3.8" "3.9" "3.10" "3.11" "3.12")
PyBin="python3"
# Path updated by find_python
PyBinPath="$(command -v "$PyBin")"

USER_OBJ_KEYS="id username discriminator verified bot email avatar"

# Status indicator for post-install notice about python venv based install.
InstalledViaVenv=0

declare -A BOT

# Get some notion of the current OS / distro name.
# This will not exhaust options, or ensure a correct name is returned.
# A good example is Raspberry Pi OS 11 which returns Debian.
Expand Down Expand Up @@ -588,121 +583,16 @@ function debug() {
fi
}

function strip_dquote() {
result="${1%\"}"
result="${result#\"}"
echo "$result"
}

function r_data() {
local data=$1
echo "$data" | sed -rn 's/(\{.+)\} ([0-9]+)$/\1}/p'
}

function r_code() {
local data=$1
echo "$data" | sed -rn 's/(\{.+)\} ([0-9]+)$/\2/p'
}

function key() {
local data=$1
local key=$2
echo "$data" | jq ".$key"
}

function r() {
local token=$1
local method=$2
local route=$3

local url="$DEFAULT_URL_BASE/$route"
debug "Attempting to load url $url with token $token"

res=$(curl -k -s \
-w " %{http_code}" \
-H "Authorization: Bot $token" \
-H "Content-Type: application/json" \
-X "$method" \
"$url" | tr -d '\n')
echo "$res"
}

function get_token_and_create_bot() {
# Set bot token
echo ""
echo "Please enter your bot token. This can be found in your discordapp developer page."
read -rp "Enter Token:" -s token
create_bot "$token"
}

function create_bot() {
local bot_token=$1

local me
local me_code
local me_data
me=$(r "$bot_token" "GET" "users/@me")
me_code=$(r_code "$me")
me_data=$(r_data "$me")

if ! [[ $me_code == "200" ]]; then
echo ""
echo "Error getting user profile, is the token correct? ($me_code $me_data)"
exit 1
else
debug "Got user profile: $me_data"
fi

for k in $USER_OBJ_KEYS; do
BOT[$k]=strip_dquote "$(key "$me_data" "$k")"
done
BOT["token"]=$bot_token

# We're logged on!
echo "Logged on with ${BOT["username"]}#${BOT["discriminator"]}"
sed -i "s/bot_token/$bot_token/g" ./config/options.ini
}

function configure_bot() {
read -rp "Would like to configure the bot for basic use? [N/y]" YesConfig
echo "You can now configure MusicBot!"
read -rp "Would like to launch the 'configure.py' tool? [N/y]" YesConfig
if [ "${YesConfig,,}" != "y" ] && [ "${YesConfig,,}" != "yes" ] ; then
echo "Open the 'config' directory, then copy and rename the example files to get started."
echo "Make sure to add your Bot token to the options.ini 'Token' option before starting."
return
fi

get_token_and_create_bot

# Set prefix, if user wants
read -rp "Would you like to change the command prefix? [N/y] " chngprefix
case $chngprefix in
[Yy]*)
echo "Please enter the prefix you'd like for your bot."
read -rp "This is what comes before all commands. The default is [!] " prefix
sed -i "s/CommandPrefix = !/CommandPrefix = $prefix/g" ./config/options.ini
;;
[Nn]*) echo "Using default prefix [!]" ;;
*) echo "Using default prefix [!]" ;;
esac

# Set owner ID, if user wants
read -rp "Would you like to automatically get the owner ID from the OAuth application? [Y/n] " accountcheck
case $accountcheck in
[Yy]*) echo "Getting owner ID from OAuth application..." ;;
[Nn]*)
read -rp "Please enter the owner ID. " ownerid
sed -i "s/OwnerID = auto/OwnerID = $ownerid/g" ./config/options.ini
;;
*) echo "Getting owner ID from OAuth application..." ;;
esac
# Enable/Disable AutoPlaylist
read -rp "Would you like to enable the autoplaylist? [Y/n] " autoplaylist
case $autoplaylist in
[Yy]*) echo "Autoplaylist enabled." ;;
[Nn]*)
echo "Autoplaylist disabled"
sed -i "s/UseAutoPlaylist = yes/UseAutoPlaylist = no/g" ./config/options.ini
;;
*) echo "Autoplaylist enabled." ;;
esac
$PyBin "${InstallDir}/configure.py"
}

#------------------------------------------CLI Arguments----------------------------------------------#
Expand Down

0 comments on commit 42850a1

Please sign in to comment.