shaiwatcher/modules/usage/usage_stats.py
Franz Rolfsvaag 0349c36880 0.4.1.0.a7
- Changed interaction check on command executions in an attempt to prevent hybrid commands from counting twice on the docsite
2025-08-16 02:56:46 +02:00

64 lines
2.4 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 once: app for slash, prefix for non-interaction Context."""
def __init__(self, bot: commands.Bot):
self.bot = bot
print("[usage] UsageStatsCog init")
# -------- slash / app-commands --------
@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))
# -------- prefix (and hybrid-as-prefix) --------
@commands.Cog.listener()
async def on_command_completion(self, ctx: commands.Context):
# If this Context came from a slash interaction (hybrid invoked via slash),
# DO NOT count here—the app listener already did.
if getattr(ctx, "interaction", None):
print("[usage] px ~~ skip: ctx.interaction is set (slash path already counted)")
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")