setup row adding/removal on guild changes, improved logging + basic command processing, add logging format to main file

This commit is contained in:
Xevion
2021-02-07 07:47:51 -06:00
parent 4527a3e427
commit 5f832de5f2
3 changed files with 60 additions and 6 deletions

View File

@@ -1,4 +1,6 @@
import logging
import re
from typing import Optional
import discord as discord
@@ -12,14 +14,47 @@ logger.setLevel(constants.LOGGING_LEVEL)
class ContestClient(discord.Client):
def __init__(self, **options) -> None:
super().__init__(**options)
self.db = ContestDatabase.create()
self.db: Optional[ContestDatabase] = None
async def on_guild_join(self, guild: discord.Guild) -> None:
logger.info(f'Added to new guild: {guild.name} ({guild.id})')
await self.db.setup_guild(guild.id)
async def on_guild_remove(self, guild: discord.Guild) -> None:
logger.info(f'Removed from guild: {guild.name} ({guild.id})')
await self.db.teardown_guild(guild.id)
async def on_ready(self):
await self.wait_until_ready()
logger.info('Bot is now ready and connected to Discord.')
guild_count = len(self.guilds)
logger.info(
f'Connected as {self.user.name}#{self.user.discriminator} to {guild_count} guild{"s" if guild_count > 1 else ""}.')
self.db = await ContestDatabase.create()
async def on_message(self, message: discord.Message) -> None:
prefix = message.guild
# Ignore self + bots
if message.author == self.user or message.author.bot:
return
# Compile a regex made for parsing commands
prefix = await self.db.get_prefix(message.guild.id)
if message.content.startswith(prefix) and len(message.content) > 1:
split = message.content[1:].split()
command = split[0]
args = split[1:]
await message.channel.send(content=f'{command} {args}')
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent) -> None:
pass
async def on_raw_reaction_add(self, payload) -> None:
async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent) -> None:
pass
async def on_raw_reaction_remove(self, payload) -> None:
async def on_raw_reaction_clear(self, payload: discord.RawReactionActionEvent) -> None:
pass
async def on_raw_reaction_clear_emoji(self, payload: discord.RawReactionClearEmojiEvent) -> None:
pass

View File

@@ -49,10 +49,12 @@ class ContestDatabase(object):
async def setup_guild(self, guild_id: int) -> None:
"""Sets up a guild in the database."""
await self.conn.execute('''INSERT INTO guild (id) VALUES (?)''', [guild_id])
await self.conn.commit()
async def set_prefix(self, guild_id: int, new_prefix: str) -> None:
"""Updates the prefix for a specific guild in the database"""
await self.conn.execute('''UPDATE guild SET prefix = ? WHERE id = ?''', [new_prefix, guild_id])
await self.conn.commit()
async def is_setup(self, guild_id: int) -> bool:
"""Checks whether the bot is setup to complete submission channel related commands."""
@@ -70,6 +72,11 @@ class ContestDatabase(object):
cur = await self.conn.cursor()
try:
await cur.execute('''SELECT prefix FROM guild WHERE id = ?''', [guild_id])
return await (await cur.fetchone())['prefix']
return (await cur.fetchone())[0]
finally:
await cur.close()
async def teardown_guild(self, guild_id: int) -> None:
"""Removes a guild from the database while completing appropriate teardown actions."""
await self.conn.execute('''DELETE FROM guild WHERE id = ?''', [guild_id])
await self.conn.commit()

14
main.py
View File

@@ -1,7 +1,19 @@
from contest import client
import logging
from contest import client, constants
if __name__ == "__main__":
bot = client.ContestClient()
logger = logging.getLogger(__file__)
logger.setLevel(constants.LOGGING_LEVEL)
logging.basicConfig(format='[%(asctime)s] [%(levelname)s] [%(funcName)s] %(message)s',
handlers=[
logging.FileHandler(f"bot.log", encoding='utf-8'),
logging.StreamHandler()
])
logger.info('Starting bot.')
with open('token.dat', 'r') as file:
bot.run(file.read())