More Documentation

This commit is contained in:
Adriene Hutchins 2020-03-02 02:01:28 -05:00
parent 997030587c
commit 38829722d5
2 changed files with 72 additions and 36 deletions

View File

@ -16,13 +16,16 @@ class BotList(commands.Cog, name='Bot List'):
"""Provides various utilities for handling BotList stuff.""" """Provides various utilities for handling BotList stuff."""
def __init__(self, bot): def __init__(self, bot):
# Main Stuff
self.bot = bot self.bot = bot
self.request = bot.request self.request = bot.request
# Tokens
# List Tokens
self.dbl_token = bot.config['DBL'] self.dbl_token = bot.config['DBL']
self.dbots_token = bot.config['DBOTS'] self.dbots_token = bot.config['DBOTS']
self.bod_token = bot.config['BOD'] self.bod_token = bot.config['BOD']
self.dblcom_token = bot.config['DBLCOM'] self.dblcom_token = bot.config['DBLCOM']
# top.gg clent # top.gg clent
self.dbl_client = dbl.DBLClient( self.dbl_client = dbl.DBLClient(
self.bot, self.dbots_token) self.bot, self.dbots_token)
@ -36,13 +39,18 @@ class BotList(commands.Cog, name='Bot List'):
dblcom_call = "https://discordbotlist.com/api" dblcom_call = "https://discordbotlist.com/api"
responses = {} responses = {}
# Calls
# bots.discord.gg # bots.discord.gg
if self.dbots_token != '': if self.dbots_token != '':
# Call Prereqs
dbots_call += f"/bots/{self.bot.user.id}/stats" dbots_call += f"/bots/{self.bot.user.id}/stats"
dbots_data = {'guildCount': len(self.bot.guilds)} dbots_data = {'guildCount': len(self.bot.guilds)}
dbots_headers = {'Authorization': self.dbots_token} dbots_headers = {'Authorization': self.dbots_token}
async with self.request.post(dbots_call,
json=dbots_data, # Call Handling
async with self.request.post(dbots_call,
json=dbots_data,
headers=dbots_headers) as resp: headers=dbots_headers) as resp:
resp_json = await resp.json() resp_json = await resp.json()
print(resp_json) print(resp_json)
@ -50,10 +58,14 @@ class BotList(commands.Cog, name='Bot List'):
# bots.ondiscord.xyz # bots.ondiscord.xyz
if self.bod_token != '': if self.bod_token != '':
# Call Prereqs
bod_call += f"/bots/{self.bot.user.id}/guilds" bod_call += f"/bots/{self.bot.user.id}/guilds"
bod_data = {'guildCount': len(self.bot.guilds)} bod_data = {'guildCount': len(self.bot.guilds)}
bod_headers = {'Authorization': self.bod_token} bod_headers = {'Authorization': self.bod_token}
async with self.request.post(bod_call,
# Call Handling
async with self.request.post(bod_call,
json=bod_data, json=bod_data,
headers=bod_headers) as resp: headers=bod_headers) as resp:
resp_json = await resp.json() resp_json = await resp.json()
@ -62,10 +74,14 @@ class BotList(commands.Cog, name='Bot List'):
# discordbotlist.com # discordbotlist.com
if self.dblcom_token != '': if self.dblcom_token != '':
# Call Prereqs
dblcom_call += f"/bots/{self.bot.user.id}/stats" dblcom_call += f"/bots/{self.bot.user.id}/stats"
dblcom_data = {'guilds': len(self.bot.guilds)} dblcom_data = {'guilds': len(self.bot.guilds)}
dblcom_headers = {'Authorization': self.dblcom_token} dblcom_headers = {'Authorization': self.dblcom_token}
async with self.request.post(dblcom_call,
# Call Handling
async with self.request.post(dblcom_call,
json=dblcom_data, json=dblcom_data,
headers=dblcom_headers) as resp: headers=dblcom_headers) as resp:
resp_json = await resp.json() resp_json = await resp.json()
@ -74,13 +90,14 @@ class BotList(commands.Cog, name='Bot List'):
# top.gg # top.gg
if self.dbl_token != '': if self.dbl_token != '':
# NOTE top.gg has a lib so it gets different handling.
try: try:
resp = await self.dbl_client.post_guild_count() resp = await self.dbl_client.post_guild_count()
responses['dbl'] = resp responses['dbl'] = resp
except Exception as e: except Exception as e:
responses['dbl'] = e responses['dbl'] = e
# Finishing up # Finalization
return responses return responses
# TODO Move to Core, hide behind check for any existing token # TODO Move to Core, hide behind check for any existing token
@ -88,11 +105,14 @@ class BotList(commands.Cog, name='Bot List'):
async def vote(self, ctx): async def vote(self, ctx):
"""Review and vote for this bot on various botlists.""" """Review and vote for this bot on various botlists."""
# Header
msg = ( msg = (
"**Thank you for wanting to help us out!**\n" "**Thank you for wanting to help us out!**\n"
"You can find us on the following lists:\n\n" "You can find us on the following lists:\n\n"
) )
# Links
# XXX This is really stupidly done, I'm going to find a way to redo it.
if self.dbots_token != '': if self.dbots_token != '':
msg += f"_bots.discord.gg_ <https://bots.discord.gg/bots/{self.bot.user.id}/>\n" msg += f"_bots.discord.gg_ <https://bots.discord.gg/bots/{self.bot.user.id}/>\n"
if self.bod_token != '': if self.bod_token != '':
@ -102,6 +122,7 @@ class BotList(commands.Cog, name='Bot List'):
if self.dbl_token != '': if self.dbl_token != '':
msg += f"_top.gg_ <https://top.gg/bot/{self.bot.user.id}/>\n" msg += f"_top.gg_ <https://top.gg/bot/{self.bot.user.id}/>\n"
# Sending
await ctx.send(msg) await ctx.send(msg)
@commands.command() @commands.command()
@ -111,16 +132,17 @@ class BotList(commands.Cog, name='Bot List'):
msg = await ctx.send("<a:loading:393852367751086090> **Updating...**") msg = await ctx.send("<a:loading:393852367751086090> **Updating...**")
responses = await self._update_logic() responses = await self._update_logic()
print(responses) # TODO Look at responses and figure out error handling print(responses) # TODO Look at responses and figure out error handling
await msg.edit(content="**Updated!**") await msg.edit(content="**Updated!**")
@tasks.loop(minutes=15.0) @tasks.loop(minutes=15.0)
async def update_stats(self): async def update_stats(self):
"""Automatically updates statistics every 15 minutes.""" """Automatically updates statistics every 15 minutes."""
responses = await self._update_logic() responses = await self._update_logic()
print(responses) print(responses) # TODO See other todo
def setup(bot): def setup(bot):
"""Adds the cog to the bot."""
bot.add_cog(BotList(bot)) bot.add_cog(BotList(bot))

66
main.py
View File

@ -23,33 +23,39 @@ class Bot(commands.Bot):
def __init__(self, **options): def __init__(self, **options):
"""Initializes the main parts of the bot.""" """Initializes the main parts of the bot."""
super().__init__(self._get_prefix_new, **options) # Logging
print('Performing initialization...\n') print('Performing initialization...\n')
# Initializes parent class
super().__init__(self._get_prefix_new, **options)
# Get Config Values # Get Config Values
with open('config.json') as f: with open('config.json') as f:
self.config = json.load(f) self.config = json.load(f)
self.prefix = self.config.get('PREFIX') self.prefix = self.config['PREFIX']
self.version = self.config.get('VERSION') self.version = self.config['VERSION']
self.maintenance = self.config.get('MAINTENANCE') self.maintenance = self.config['MAINTENANCE']
self.description = self.config.get('DESCRIPTION') self.description = self.config['DESCRIPTION']
self.case_insensitive = self.config['CASE_INSENSITIVE']
# Get Instances # Get Instances
with open('searxes.txt') as f: with open('searxes.txt') as f:
self.instances = f.read().split('\n') self.instances = f.read().split('\n')
# Logging
print('Initialization complete.\n\n') print('Initialization complete.\n\n')
async def _get_prefix_new(self, bot, msg): async def _get_prefix_new(self, bot, msg):
"""Full flexible check for prefix.""" """More flexible check for prefix."""
# Adds empty prefix if in DMs
if isinstance(msg.channel, discord.DMChannel) and self.config['PREFIXLESS_DMS']: if isinstance(msg.channel, discord.DMChannel) and self.config['PREFIXLESS_DMS']:
# Adds empty prefix if in DMs plus_empty = self.prefix.copy()
plus_none = self.prefix.copy() plus_empty.append('')
plus_none.append('') return commands.when_mentioned_or(*plus_empty)(bot, msg)
return commands.when_mentioned_or(*plus_none)(bot, msg) # Keeps regular if not
else: else:
# Keeps regular if not
return commands.when_mentioned_or(*self.prefix)(bot, msg) return commands.when_mentioned_or(*self.prefix)(bot, msg)
async def on_ready(self): async def on_ready(self):
@ -61,7 +67,8 @@ class Bot(commands.Bot):
if self.description == '': if self.description == '':
self.description = self.appinfo.description self.description = self.appinfo.description
# EXTENSION ENTRY POINT # NOTE Extension Entry Point
# Loads core, which loads all other extensions
self.load_extension('extensions.core') self.load_extension('extensions.core')
# Logging # Logging
@ -73,48 +80,52 @@ class Bot(commands.Bot):
print(msg) print(msg)
async def on_message(self, message): async def on_message(self, message):
"""Handles what the bot does whenever a message comes across."""
# Prerequisites # Prerequisites
mentions = [self.user.mention, f'<@!{self.user.id}>'] mentions = [self.user.mention, f'<@!{self.user.id}>']
ctx = await self.get_context(message) ctx = await self.get_context(message)
# Handling # Handling
# Turn away bots
if message.author.bot: if message.author.bot:
# Turn away bots
return return
# Ignore blocked users
elif message.author.id in self.config.get('BLOCKED'): elif message.author.id in self.config.get('BLOCKED'):
# Ignore blocked users
return return
# Maintenance mode
elif self.maintenance and not message.author.is_owner(): elif self.maintenance and not message.author.is_owner():
# Maintenance mode
return return
# Empty ping for assistance
elif message.content in mentions and self.config.get('MENTION_ASSIST'): elif message.content in mentions and self.config.get('MENTION_ASSIST'):
# Empty ping for assistance
assist_msg = ( assist_msg = (
"**Hi there! How can I help?**\n\n" "**Hi there! How can I help?**\n\n"
# Two New Lines Here # Two New Lines Here
f"You may use **{self.user.mention} `term here`** to search, " f"You may use **{self.user.mention} `term here`** to search, "
f"or **{self.user.mention} `help`** for assistance.") f"or **{self.user.mention} `help`** for assistance.")
await ctx.send(assist_msg) await ctx.send(assist_msg)
# Move on to command handling
else: else:
# Move on to command handling
await self.process_commands(message) await self.process_commands(message)
# Creates Bot object
bot = Bot( bot = Bot()
case_insensitive=True)
@bot.listen() @bot.listen()
async def on_command_error(ctx, error): async def on_command_error(ctx, error):
"""Handles all errors stemming from ext.commands."""
# Lets other cogs handle CommandNotFound.
# Change this if you want command not found handling
if isinstance(error, commands.CommandNotFound): if isinstance(error, commands.CommandNotFound):
# Lets other cogs handle this.
# Change this if you want command not found handling.
return return
# Provides a very pretty embed if something's actually a dev's fault.
elif isinstance(error, commands.CommandInvokeError): elif isinstance(error, commands.CommandInvokeError):
# Provides a very pretty embed if something's actually a dev's fault.
# Prerequisites # Prerequisites
error = error.original error = error.original
_traceback = traceback.format_tb(error.__traceback__) _traceback = traceback.format_tb(error.__traceback__)
@ -149,10 +160,13 @@ async def on_command_error(ctx, error):
if len(trace_content) > 1024 if len(trace_content) > 1024
else trace_content) else trace_content)
# Sending
await ctx.send(embed_fallback, embed=error_embed) await ctx.send(embed_fallback, embed=error_embed)
# If anything else goes wrong, just go ahead and send it in chat.
else: else:
# If anything else goes wrong, just go ahead and send it in chat.
await ctx.send(error) await ctx.send(error)
# NOTE Bot Entry Point
# Starts the bot
bot.run(bot.config['TOKEN']) bot.run(bot.config['TOKEN'])