Skip to content

Instantly share code, notes, and snippets.

@Stalruth
Created August 11, 2021 11:08
Show Gist options
  • Save Stalruth/8aa223c36db7ac89ce24efc34021c738 to your computer and use it in GitHub Desktop.
Save Stalruth/8aa223c36db7ac89ce24efc34021c738 to your computer and use it in GitHub Desktop.
Prints the commands of the Discord Bot given.
#!/usr/bin/env python3
import urllib.request as request
import urllib.parse as parse
import base64
import json
import os
import argparse
base_url = 'https://discord.com/api/v9'
argument_parser = argparse.ArgumentParser(description='Print bot commands as Markdown.\n\nGets APP_ID and CLIENT_SECRET from environment if available, prompts otherwise.')
argument_parser.add_argument('--commands', action='store', nargs='?', help='File contaning the commands as retrieved from Discord\'s API.', metavar='FILE')
def get_bearer(client_id, client_secret):
url = base_url + '/oauth2/token'
body = {
'grant_type': 'client_credentials',
'scope': 'applications.commands.update',
}
data = parse.urlencode(body).encode('ascii')
req = request.Request(url, data)
credentials = base64.b64encode(f'{client_id}:{client_secret}'.encode('ascii'))
req.add_header('Authorization', 'Basic %s' % credentials.decode('ascii'))
req.add_header('User-Agent', 'Bot Command Summariser')
with request.urlopen(req) as response:
return json.loads(response.read().decode('utf-8'))
def get_commands_from_api(auth_type, auth_token, app_id, guild_id=None):
url = base_url + f'/applications/{app_id}'
if guild_id is not None:
url += f'/guilds/{guild_id}'
url += '/commands'
headers = {
'Authorization': f'{auth_type} {auth_token}',
'Content-Type': 'application/json',
'User-Agent': 'Bot Command Summariser',
}
req = request.Request(url, data=None, headers=headers)
with request.urlopen(req) as response:
return response.read().decode('utf-8')
def get_commands():
command_file = argument_parser.parse_args().commands
if command_file is not None:
with open(command_file, 'r') as comfile:
return json.load(comfile)
BEARER_TOKEN = None
APP_ID = None
try:
APP_ID = os.environ['APP_ID']
except KeyError:
APP_ID = input('App ID: ')
try:
BEARER_TOKEN = os.environ['BEARER_TOKEN']
except KeyError:
CLIENT_SECERT = None
try:
CLIENT_SECRET = os.environ['CLIENT_SECRET']
except KeyError:
CLIENT_SECRET = input('Client Secret: ')
BEARER_TOKEN = get_bearer(APP_ID, CLIENT_SECRET)['access_token']
return json.loads(get_commands_from_api('Bearer', BEARER_TOKEN, APP_ID))
def format_options(options, level, command):
if len(options) == 0:
return ''
TYPES = [
'',
'Subcommand',
'Subcommand Group',
'String',
'Integer',
'Boolean',
'User',
'Channel',
'Role',
'Mentionable',
'Number',
]
result = ''
progress = ''
for option in options:
if option['type'] == 1:
result += format_commands(options, command, level)
break;
if option.get('required', False) and progress != 'R':
progress = 'R'
result += ('#'*level) + ' Required Arguments:\n\n'
elif not option.get('required', False) and progress != 'O':
if progress == 'R':
result += '\n'
progress = 'O'
result += ('#'*level) + ' Optional Arguments:\n\n'
result += '- ' + option['name'] + ' (' + TYPES[option['type']] + '): ' + option['description'] + '\n'
return result + '\n'
def format_commands(commands, super_command=None, level=2):
COMMAND_TYPES: ['', 'Chat input', 'User Menu', 'Message Menu']
result = ''
for command in commands:
full_name = super_command + ' ' + command['name'] if super_command is not None else command['name']
isChat = command['type'] == 1 or super_command is not None
command_name = ('`/' + full_name + '`') if isChat else '(' + COMMAND_TYPES[command['type']] + ') ' + fullName
result += ('#'*level) + ' ' + command_name + '\n\n'
result += command['description'] + '\n\n'
options = []
try:
options = command['options']
except KeyError:
pass
result += format_options(options, level + 1, command['name'])
return result
if __name__ == '__main__':
commands = get_commands()
print(format_commands(commands))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment