shaiwatcher/modules/usage/usage_stats.py
Franz Rolfsvaag dab1e4e9e0 0.4.1.0.a6
- I forgot hybrid commands call two triggers whenever executed, thus messing with the counter on the docsite
  - *Let's see if this fixes things..*
2025-08-16 02:50:57 +02:00

61 lines
2.3 KiB
Python

# modules/usage/usage_stats.py
from __future__ import annotations
from discord.ext import commands
import discord
COUNTER_KEY_PREFIX = "cmd::"
def _key_from_app(cmd: discord.app_commands.Command) -> str:
name = getattr(cmd, "qualified_name", None) or getattr(cmd, "name", "unknown")
return f"{COUNTER_KEY_PREFIX}{name}"
def _key_from_ctx(ctx: commands.Context) -> str:
c = getattr(ctx, "command", None)
name = getattr(c, "qualified_name", None) or getattr(c, "name", "unknown")
return f"{COUNTER_KEY_PREFIX}{name}"
class UsageStatsCog(commands.Cog):
"""Count command runs without double-counting hybrids invoked as slash."""
def __init__(self, bot: commands.Bot):
self.bot = bot
print("[usage] UsageStatsCog init")
@commands.Cog.listener()
async def on_app_command_completion(self, interaction: discord.Interaction, command: discord.app_commands.Command):
dm = getattr(self.bot, "data_manager", None)
if not dm:
return
try:
key = _key_from_app(command)
newv = dm.incr_counter(key, 1)
print(f"[usage] app ++ {key} -> {newv}")
except Exception as e:
print("[usage] app !! incr failed:", repr(e))
@commands.Cog.listener()
async def on_command_completion(self, ctx: commands.Context):
# If a HybridCommand was invoked via slash, the app listener already counted it.
if isinstance(getattr(ctx, "command", None), commands.HybridCommand) and getattr(ctx, "interaction", None):
print("[usage] px ~~ hybrid-as-slash; ignored (already counted in app)")
return
dm = getattr(self.bot, "data_manager", None)
if not dm:
return
try:
key = _key_from_ctx(ctx)
newv = dm.incr_counter(key, 1)
print(f"[usage] px ++ {key} -> {newv}")
except Exception as e:
print("[usage] px !! incr failed:", repr(e))
async def setup(bot: commands.Bot):
# Avoid double registration if extensions are discovered/reloaded twice
if getattr(bot, "_usage_stats_loaded", False):
print("[usage] UsageStatsCog already loaded; skipping duplicate add")
return
await bot.add_cog(UsageStatsCog(bot))
bot._usage_stats_loaded = True
print("[usage] UsageStatsCog loaded")