Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use synced slash commands and logging module #142

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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(
Expand All @@ -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})',
)
Expand All @@ -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.'
Expand All @@ -180,4 +185,14 @@ 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()
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions src/heckbot/adapter/sqlite_adaptor.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from __future__ import annotations

import logging
import sqlite3
import threading
from typing import Any
from typing import Optional

logger = logging.getLogger(__name__)


class SqliteAdaptor:
def __init__(
Expand Down Expand Up @@ -40,7 +43,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}',
)
Expand All @@ -55,7 +58,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}',
)
3 changes: 3 additions & 0 deletions src/heckbot/cogs/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import logging
from typing import Literal

from discord.ext import commands
Expand All @@ -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',
Expand Down
4 changes: 4 additions & 0 deletions src/heckbot/cogs/events.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import logging

import discord
from discord import TextChannel
from discord.ext import commands
Expand All @@ -8,6 +10,8 @@

from bot import HeckBot

logger = logging.getLogger(__name__)


class Events(commands.Cog):
def __init__(
Expand Down
3 changes: 3 additions & 0 deletions src/heckbot/cogs/gif.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import logging
import os

import aiohttp
Expand All @@ -9,6 +10,8 @@

from bot import HeckBot

logger = logging.getLogger(__name__)


class Gif(commands.Cog):
"""
Expand Down
3 changes: 3 additions & 0 deletions src/heckbot/cogs/message.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import logging

import discord
from discord.ext import commands
Expand All @@ -10,6 +11,8 @@

from bot import HeckBot

logger = logging.getLogger(__name__)


class Message(commands.Cog):
"""
Expand Down
3 changes: 3 additions & 0 deletions src/heckbot/cogs/moderation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import logging
import traceback

import discord
Expand All @@ -13,6 +14,8 @@

from bot import HeckBot

logger = logging.getLogger(__name__)


class Moderation(commands.Cog):
def __init__(
Expand Down
9 changes: 6 additions & 3 deletions src/heckbot/cogs/poll.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import logging
import random
from collections import namedtuple
from datetime import datetime
Expand All @@ -22,6 +23,8 @@
from bot import db_conn
from bot import HeckBot

logger = logging.getLogger(__name__)

Bounds: namedtuple = namedtuple(
'Bounds',
['min', 'max'],
Expand Down Expand Up @@ -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',
)
Expand Down
3 changes: 3 additions & 0 deletions src/heckbot/cogs/react.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import logging

import discord
from discord.ext import commands
Expand All @@ -10,6 +11,8 @@

from bot import HeckBot

logger = logging.getLogger(__name__)


class React(commands.Cog):
"""
Expand Down
18 changes: 14 additions & 4 deletions src/heckbot/cogs/roles.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import logging

import discord
from discord import RawReactionActionEvent
from discord import Role
Expand All @@ -9,6 +11,8 @@

from bot import HeckBot

logger = logging.getLogger(__name__)


class Roles(commands.Cog):
"""
Expand Down Expand Up @@ -42,7 +46,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
Expand Down Expand Up @@ -81,7 +86,9 @@ 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 = []
Expand All @@ -93,7 +100,9 @@ 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,
Expand All @@ -114,7 +123,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:
Expand Down
2 changes: 1 addition & 1 deletion src/heckbot/types/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down
Loading