Command stats

This commit is contained in:
stijndcl 2022-09-20 14:47:26 +02:00
parent 7517f844d8
commit 23edc51dbf
4 changed files with 141 additions and 29 deletions

View file

@ -0,0 +1,38 @@
from datetime import datetime
from typing import Optional, Union
from discord import app_commands
from discord.ext import commands
from sqlalchemy.ext.asyncio import AsyncSession
from database.schemas import CommandStats
__all__ = ["register_command_invocation"]
CommandT = Union[commands.Command, app_commands.Command, app_commands.ContextMenu]
async def register_command_invocation(
session: AsyncSession, ctx: commands.Context, command: Optional[CommandT], timestamp: datetime
):
"""Create an entry for a command invocation"""
if command is None:
return
# Check the type of invocation
context_menu = isinstance(command, app_commands.ContextMenu)
# (This is a bit uglier but it accounts for hybrid commands)
slash = isinstance(command, app_commands.Command) or (ctx.interaction is not None and not context_menu)
stats = CommandStats(
command=command.qualified_name.lower(),
timestamp=timestamp,
user_id=ctx.author.id,
slash=slash,
context_menu=context_menu,
)
session.add(stats)
await session.commit()

View file

@ -27,6 +27,7 @@ __all__ = [
"Bank",
"Birthday",
"Bookmark",
"CommandStats",
"CustomCommand",
"CustomCommandAlias",
"DadJoke",
@ -95,6 +96,18 @@ class Bookmark(Base):
user: User = relationship("User", back_populates="bookmarks", uselist=False, lazy="selectin")
class CommandStats(Base):
"""Metrics on how often commands are used"""
__tablename__ = "command_stats"
command_stats_id: int = Column(Integer, primary_key=True)
command: str = Column(Text, nullable=False)
timestamp: datetime = Column(DateTime(timezone=True), nullable=False)
user_id: int = Column(BigInteger, nullable=False)
slash: bool = Column(Boolean, nullable=False)
context_menu: bool = Column(Boolean, nullable=False)
class CustomCommand(Base):
"""Custom commands to fill the hole Dyno couldn't"""