Skip to content

Instantly share code, notes, and snippets.

@imayhaveborkedit
Last active July 7, 2024 08:24
Show Gist options
  • Save imayhaveborkedit/9ee4b6fb65a01ac8235214cafa7aaf52 to your computer and use it in GitHub Desktop.
Save imayhaveborkedit/9ee4b6fb65a01ac8235214cafa7aaf52 to your computer and use it in GitHub Desktop.
Context menus in cogs
from utils import contextutil
class General(commands.Cog):
def __init__(self, bot):
self.bot: Bot = bot
self.menus = contextutil.ContextMenuHolder(self)
self.menus.load_commands()
self.menus.add_commands()
async def cog_load(self):
# I dont think it matters if loading is done here or in init but it works for me
pass
async def cog_unload(self):
self.menus.remove_commands()
self.menus.clear()
@contextutil.context_menu(name="Do something")
async def something(self, interaction: Intr, message: discord.Message):
...
# -*- coding: utf-8 -*-
import inspect
from discord import app_commands
class ContextMenuHolder:
def __init__(self, cog):
self.cog = cog
self.commands = []
def load_commands(self):
for name, member in inspect.getmembers(self.cog):
if getattr(member, "__context_menu_hack__", False):
menu = app_commands.ContextMenu(**member.__context_menu_hack_kwargs__, callback=member)
self.commands.append(menu)
def add_commands(self):
for menu in self.commands:
self.cog.bot.tree.add_command(menu)
def remove_command(self, command):
self.cog.bot.tree.remove_command(command.name, type=command.type)
def remove_commands(self):
for menu in self.commands:
self.remove_command(menu)
def clear(self):
self.commands.clear()
def context_menu(**kwargs):
def wrapper(func):
func.__context_menu_hack__ = True
func.__context_menu_hack_kwargs__ = kwargs.copy()
return func
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment