From 132763326ddf27e13caf388bfe46fc4f5b41c15a Mon Sep 17 00:00:00 2001 From: Julian Espada Date: Mon, 27 Nov 2023 21:55:06 -0500 Subject: [PATCH 1/2] Use logging module --- bot.py | 25 +++++++++++++++++++++---- requirements.txt | 1 + src/heckbot/adapter/sqlite_adaptor.py | 8 ++++++-- src/heckbot/cogs/config.py | 3 +++ src/heckbot/cogs/events.py | 3 +++ src/heckbot/cogs/gif.py | 3 +++ src/heckbot/cogs/message.py | 3 +++ src/heckbot/cogs/moderation.py | 3 +++ src/heckbot/cogs/poll.py | 9 ++++++--- src/heckbot/cogs/react.py | 3 +++ src/heckbot/cogs/roles.py | 17 ++++++++++++----- src/heckbot/types/constants.py | 2 +- 12 files changed, 65 insertions(+), 15 deletions(-) diff --git a/bot.py b/bot.py index c1621f2..4aa95e8 100644 --- a/bot.py +++ b/bot.py @@ -19,6 +19,7 @@ from typing import cast import discord +import logging from discord import Intents from discord import TextChannel from discord.ext import commands @@ -29,6 +30,10 @@ from heckbot.types.constants import BOT_COMMAND_PREFIX from heckbot.types.constants import BOT_CUSTOM_STATUS from heckbot.types.constants import PRIMARY_GUILD_ID +from discord.ext.commands import Bot +from discord.ext.commands import Context + +logger = logging.getLogger(__name__) TASK_LOOP_PERIOD = 5 # seconds @@ -136,7 +141,7 @@ async def setup_hook( try: await self.load_extension(f'src.heckbot.cogs.{cog}') except Exception as ex: - print(f'Could not load extension {cog}: {ex}') + logger.error(f'Could not load extension {cog}: {ex}') raise ex async def after_ready( @@ -158,7 +163,7 @@ async def after_ready( # alert channels of bot online status for guild in self.guilds: - print( + logger.info( f'{self.user} has connected to the following guild: ' f'{guild.name}(id: {guild.id})', ) @@ -169,7 +174,7 @@ async def after_ready( self.config.get_message(guild.id, 'welcomeMessage'), ) - print( + logger.debug( f'----------------HeckBot---------------------' f'\nBot is online as user {self.user}' f'\nConnected to {(len(self.guilds))} guilds.' @@ -180,4 +185,16 @@ async def after_ready( if __name__ == '__main__': random.seed(0) - HeckBot().run() + bot = HeckBot() + + + @bot.command() + async def sync(ctx: Context[Bot]): + if ctx.author.id == 277859399903608834: + await bot.tree.sync() + logger.info('Command tree synced.') + else: + await ctx.send('You must be the owner to use this command!') + + + bot.run() diff --git a/requirements.txt b/requirements.txt index 362c086..30f6ddc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,6 +3,7 @@ colorama~=0.4.6 discord~=2.3.2 dpytest~=0.7.0 heckbot +logging~=0.4.9.6 pynacl~=1.5.0 pynamodb~=5.5.0 pytest~=7.4.3 diff --git a/src/heckbot/adapter/sqlite_adaptor.py b/src/heckbot/adapter/sqlite_adaptor.py index d255ed9..cff239b 100644 --- a/src/heckbot/adapter/sqlite_adaptor.py +++ b/src/heckbot/adapter/sqlite_adaptor.py @@ -5,6 +5,10 @@ from typing import Any from typing import Optional +import logging + +logger = logging.getLogger(__name__) + class SqliteAdaptor: def __init__( @@ -40,7 +44,7 @@ def run_query( with self._lock: return self.cursor.execute(query, params).fetchall() except sqlite3.Error as ex: - print( + logger.warning( f'Got exception {ex} when running query ' f'{query} with params {params}', ) @@ -55,7 +59,7 @@ def run_query_many( with self._lock: return self.cursor.executemany(query, params_list).fetchall() except sqlite3.Error as ex: - print( + logger.error( f'Got exception {ex} when running query many ' f'{query} with params list {params_list}', ) diff --git a/src/heckbot/cogs/config.py b/src/heckbot/cogs/config.py index 2599f2c..35e6655 100644 --- a/src/heckbot/cogs/config.py +++ b/src/heckbot/cogs/config.py @@ -2,6 +2,7 @@ from typing import Literal +import logging from discord.ext import commands from discord.ext.commands import Bot from discord.ext.commands import Context @@ -9,6 +10,8 @@ from bot import HeckBot +logger = logging.getLogger(__name__) + ConfigCommand = Literal[ 'add', 'create', 'update', 'set', 'remove', 'unset', 'delete', 'get', 'read', 'load', 'list', diff --git a/src/heckbot/cogs/events.py b/src/heckbot/cogs/events.py index 7b106aa..da3cf57 100644 --- a/src/heckbot/cogs/events.py +++ b/src/heckbot/cogs/events.py @@ -1,6 +1,7 @@ from __future__ import annotations import discord +import logging from discord import TextChannel from discord.ext import commands from heckbot.types.constants import PRIMARY_GUILD_ID @@ -8,6 +9,8 @@ from bot import HeckBot +logger = logging.getLogger(__name__) + class Events(commands.Cog): def __init__( diff --git a/src/heckbot/cogs/gif.py b/src/heckbot/cogs/gif.py index 8a0bb0a..fcbbd5f 100644 --- a/src/heckbot/cogs/gif.py +++ b/src/heckbot/cogs/gif.py @@ -3,12 +3,15 @@ import os import aiohttp +import logging from discord.ext import commands from discord.ext.commands import Bot from discord.ext.commands import Context from bot import HeckBot +logger = logging.getLogger(__name__) + class Gif(commands.Cog): """ diff --git a/src/heckbot/cogs/message.py b/src/heckbot/cogs/message.py index 2328cfe..153a953 100644 --- a/src/heckbot/cogs/message.py +++ b/src/heckbot/cogs/message.py @@ -3,6 +3,7 @@ import asyncio import discord +import logging from discord.ext import commands from discord.ext.commands import Bot from discord.ext.commands import Context @@ -10,6 +11,8 @@ from bot import HeckBot +logger = logging.getLogger(__name__) + class Message(commands.Cog): """ diff --git a/src/heckbot/cogs/moderation.py b/src/heckbot/cogs/moderation.py index 12d2017..94b7a41 100644 --- a/src/heckbot/cogs/moderation.py +++ b/src/heckbot/cogs/moderation.py @@ -3,6 +3,7 @@ import traceback import discord +import logging from discord import Embed from discord import Member from discord import Role @@ -13,6 +14,8 @@ from bot import HeckBot +logger = logging.getLogger(__name__) + class Moderation(commands.Cog): def __init__( diff --git a/src/heckbot/cogs/poll.py b/src/heckbot/cogs/poll.py index 0dbaaf5..996b5b4 100644 --- a/src/heckbot/cogs/poll.py +++ b/src/heckbot/cogs/poll.py @@ -6,6 +6,7 @@ from datetime import timedelta from typing import Sequence +import logging from discord import Forbidden from discord import Message from discord import TextChannel @@ -22,6 +23,8 @@ from bot import db_conn from bot import HeckBot +logger = logging.getLogger(__name__) + Bounds: namedtuple = namedtuple( 'Bounds', ['min', 'max'], @@ -166,17 +169,17 @@ def format_roll_results( # TODO input validation on roll requests which don't fit on # mobile, maybe this could be a config option? if max_dice_strlen > RESULT_DICE_LENGTH_BOUNDS.max: - print( + logger.warning( 'Warning: dice string exceeds the set ' 'limit for optimal mobile display', ) if max_rolls_strlen > RESULT_ROLLS_LENGTH_BOUNDS.max: - print( + logger.warning( 'Warning: rolls string exceeds the set ' 'limit for optimal mobile display', ) if max_sum_strlen > RESULT_SUM_LENGTH_BOUNDS.max: - print( + logger.warning( 'Warning: sum string exceeds the set ' 'limit for optimal mobile display', ) diff --git a/src/heckbot/cogs/react.py b/src/heckbot/cogs/react.py index 82173e1..601356d 100644 --- a/src/heckbot/cogs/react.py +++ b/src/heckbot/cogs/react.py @@ -3,6 +3,7 @@ import asyncio import discord +import logging from discord.ext import commands from discord.ext.commands import Bot from discord.ext.commands import Context @@ -10,6 +11,8 @@ from bot import HeckBot +logger = logging.getLogger(__name__) + class React(commands.Cog): """ diff --git a/src/heckbot/cogs/roles.py b/src/heckbot/cogs/roles.py index b4f7537..3a7feb6 100644 --- a/src/heckbot/cogs/roles.py +++ b/src/heckbot/cogs/roles.py @@ -1,13 +1,16 @@ from __future__ import annotations import discord +import logging from discord import RawReactionActionEvent from discord import Role from discord.ext import commands from discord.ext.commands import Context -from heckbot.adapter.sqlite_adaptor import SqliteAdaptor from bot import HeckBot +from heckbot.adapter.sqlite_adaptor import SqliteAdaptor + +logger = logging.getLogger(__name__) class Roles(commands.Cog): @@ -42,7 +45,8 @@ def __init__( role_react TEXT NOT NULL, role_opt_in BOOLEAN NOT NULL DEFAULT TRUE, PRIMARY KEY (guild_id, role_name), - FOREIGN KEY (role_category) REFERENCES role_categories (role_category)); + FOREIGN KEY (role_category) + REFERENCES role_categories (role_category)); ''') self._db.run_query('''\ CREATE TABLE IF NOT EXISTS role_messages @@ -81,7 +85,8 @@ async def create_role( content = message.content + f'\n{emoji} for {description}' await message.edit(content=content) await message.add_reaction(emoji) - roles_params_list.append((guild_id, name, description, category, emoji)) + roles_params_list.append( + (guild_id, name, description, category, emoji)) if not category_exists: channels = {r['channel_id'] for r in results} message_params_list = [] @@ -93,7 +98,8 @@ async def create_role( f'{emoji} for {description}', ) await message.add_reaction(emoji) - message_params_list.append((guild_id, str(channel.id), str(message.id))) + message_params_list.append( + (guild_id, str(channel.id), str(message.id))) self._db.run_query_many( '''INSERT INTO role_messages (guild_id, channel_id, message_id) VALUES (?, ?, ?);''', message_params_list, @@ -114,7 +120,8 @@ async def delete_role( ): guild_id = str(ctx.guild.id) role_rows = self._db.run_query( - '''SELECT role_react, role_description, role_category, role_react FROM roles + '''SELECT role_react, role_description, role_category, role_react + FROM roles WHERE guild_id=? AND role_name=?;''', (guild_id, name), ) if len(role_rows) < 1: diff --git a/src/heckbot/types/constants.py b/src/heckbot/types/constants.py index 2b6d014..c5a2515 100644 --- a/src/heckbot/types/constants.py +++ b/src/heckbot/types/constants.py @@ -5,7 +5,7 @@ WELCOME_CHANNEL_ID = 744611387371683962 ADMIN_CONSOLE_CHANNEL_ID = 744611387371683962 -BOT_COMMAND_PREFIX = '!' +BOT_COMMAND_PREFIX = '/' BOT_CUSTOM_STATUS = f'{BOT_COMMAND_PREFIX}help' From 16cc4478898d5c67718feba5e96d22fa01bfbd5d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 28 Nov 2023 02:55:49 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- bot.py | 2 -- src/heckbot/adapter/sqlite_adaptor.py | 3 +-- src/heckbot/cogs/config.py | 2 +- src/heckbot/cogs/events.py | 3 ++- src/heckbot/cogs/gif.py | 2 +- src/heckbot/cogs/message.py | 2 +- src/heckbot/cogs/moderation.py | 2 +- src/heckbot/cogs/poll.py | 2 +- src/heckbot/cogs/react.py | 2 +- src/heckbot/cogs/roles.py | 15 +++++++++------ 10 files changed, 18 insertions(+), 17 deletions(-) diff --git a/bot.py b/bot.py index 4aa95e8..3028381 100644 --- a/bot.py +++ b/bot.py @@ -187,7 +187,6 @@ async def after_ready( random.seed(0) bot = HeckBot() - @bot.command() async def sync(ctx: Context[Bot]): if ctx.author.id == 277859399903608834: @@ -196,5 +195,4 @@ async def sync(ctx: Context[Bot]): else: await ctx.send('You must be the owner to use this command!') - bot.run() diff --git a/src/heckbot/adapter/sqlite_adaptor.py b/src/heckbot/adapter/sqlite_adaptor.py index cff239b..52153e2 100644 --- a/src/heckbot/adapter/sqlite_adaptor.py +++ b/src/heckbot/adapter/sqlite_adaptor.py @@ -1,12 +1,11 @@ from __future__ import annotations +import logging import sqlite3 import threading from typing import Any from typing import Optional -import logging - logger = logging.getLogger(__name__) diff --git a/src/heckbot/cogs/config.py b/src/heckbot/cogs/config.py index 35e6655..8690b3d 100644 --- a/src/heckbot/cogs/config.py +++ b/src/heckbot/cogs/config.py @@ -1,8 +1,8 @@ from __future__ import annotations +import logging from typing import Literal -import logging from discord.ext import commands from discord.ext.commands import Bot from discord.ext.commands import Context diff --git a/src/heckbot/cogs/events.py b/src/heckbot/cogs/events.py index da3cf57..b177a35 100644 --- a/src/heckbot/cogs/events.py +++ b/src/heckbot/cogs/events.py @@ -1,7 +1,8 @@ from __future__ import annotations -import discord import logging + +import discord from discord import TextChannel from discord.ext import commands from heckbot.types.constants import PRIMARY_GUILD_ID diff --git a/src/heckbot/cogs/gif.py b/src/heckbot/cogs/gif.py index fcbbd5f..12ac41c 100644 --- a/src/heckbot/cogs/gif.py +++ b/src/heckbot/cogs/gif.py @@ -1,9 +1,9 @@ from __future__ import annotations +import logging import os import aiohttp -import logging from discord.ext import commands from discord.ext.commands import Bot from discord.ext.commands import Context diff --git a/src/heckbot/cogs/message.py b/src/heckbot/cogs/message.py index 153a953..de68aec 100644 --- a/src/heckbot/cogs/message.py +++ b/src/heckbot/cogs/message.py @@ -1,9 +1,9 @@ from __future__ import annotations import asyncio +import logging import discord -import logging from discord.ext import commands from discord.ext.commands import Bot from discord.ext.commands import Context diff --git a/src/heckbot/cogs/moderation.py b/src/heckbot/cogs/moderation.py index 94b7a41..fbb2cc1 100644 --- a/src/heckbot/cogs/moderation.py +++ b/src/heckbot/cogs/moderation.py @@ -1,9 +1,9 @@ from __future__ import annotations +import logging import traceback import discord -import logging from discord import Embed from discord import Member from discord import Role diff --git a/src/heckbot/cogs/poll.py b/src/heckbot/cogs/poll.py index 996b5b4..49977e6 100644 --- a/src/heckbot/cogs/poll.py +++ b/src/heckbot/cogs/poll.py @@ -1,12 +1,12 @@ from __future__ import annotations +import logging import random from collections import namedtuple from datetime import datetime from datetime import timedelta from typing import Sequence -import logging from discord import Forbidden from discord import Message from discord import TextChannel diff --git a/src/heckbot/cogs/react.py b/src/heckbot/cogs/react.py index 601356d..77225e1 100644 --- a/src/heckbot/cogs/react.py +++ b/src/heckbot/cogs/react.py @@ -1,9 +1,9 @@ from __future__ import annotations import asyncio +import logging import discord -import logging from discord.ext import commands from discord.ext.commands import Bot from discord.ext.commands import Context diff --git a/src/heckbot/cogs/roles.py b/src/heckbot/cogs/roles.py index 3a7feb6..f12a5f2 100644 --- a/src/heckbot/cogs/roles.py +++ b/src/heckbot/cogs/roles.py @@ -1,14 +1,15 @@ from __future__ import annotations -import discord import logging + +import discord from discord import RawReactionActionEvent from discord import Role from discord.ext import commands from discord.ext.commands import Context +from heckbot.adapter.sqlite_adaptor import SqliteAdaptor from bot import HeckBot -from heckbot.adapter.sqlite_adaptor import SqliteAdaptor logger = logging.getLogger(__name__) @@ -45,7 +46,7 @@ def __init__( role_react TEXT NOT NULL, role_opt_in BOOLEAN NOT NULL DEFAULT TRUE, PRIMARY KEY (guild_id, role_name), - FOREIGN KEY (role_category) + FOREIGN KEY (role_category) REFERENCES role_categories (role_category)); ''') self._db.run_query('''\ @@ -86,7 +87,8 @@ async def create_role( await message.edit(content=content) await message.add_reaction(emoji) roles_params_list.append( - (guild_id, name, description, category, emoji)) + (guild_id, name, description, category, emoji), + ) if not category_exists: channels = {r['channel_id'] for r in results} message_params_list = [] @@ -99,7 +101,8 @@ async def create_role( ) await message.add_reaction(emoji) message_params_list.append( - (guild_id, str(channel.id), str(message.id))) + (guild_id, str(channel.id), str(message.id)), + ) self._db.run_query_many( '''INSERT INTO role_messages (guild_id, channel_id, message_id) VALUES (?, ?, ?);''', message_params_list, @@ -120,7 +123,7 @@ async def delete_role( ): guild_id = str(ctx.guild.id) role_rows = self._db.run_query( - '''SELECT role_react, role_description, role_category, role_react + '''SELECT role_react, role_description, role_category, role_react FROM roles WHERE guild_id=? AND role_name=?;''', (guild_id, name), )