如何在DM中使用Discord斜杠命令



我想在DM中使用斜杠命令。把这个简单的test.py文件放在cogs/文件夹中。

import discord
from discord.ext import commands
from discord import app_commands
class Test(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Loaded test command cog.")
@app_commands.command(name="test", description="Test command")
async def test(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Hello')
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Test(bot))

在cogs文件夹之外是我的launch_bot.py文件,它启动了bot:

import discord
from discord.ext import commands
import json
with open("cogs/jsons/settings.json") as json_file:
data_dict = json.load(json_file)
guild_id = data_dict["guild_id"]
class MyBot(commands.Bot):

def __init__(self) -> None:
super().__init__(
command_prefix = "kt$", 
intents = discord.Intents.all(),
tree_cls=CustomCommandTree)

async def setup_hook(self) -> None:
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
await bot.tree.sync(guild=discord.Object(id=guild_id))

async def on_ready(self):
application_info = await self.application_info()
bot_owner = application_info.owner
await bot_owner.create_dm()
self.bot_owner_dm_channel = bot_owner.dm_channel

await self.change_presence(activity=discord.Game(presence_message))

print(f"Logged in asntName: {self.user.name}ntID: {self.user.id}")
print(f"Running pycord version: {discord.__version__}")
print(f"Synced commands to guild with id {guild_id}.")
bot = MyBot()
bot.run(bot_token)

我试着按照链接中描述的说明操作,但我没有指定公会,所以这不起作用。医生说它应该有效,但对我来说没有任何想法?

如果您使用pycord,则至少在默认情况下,对于me命令在dm中是可用的如果你需要的话,我会告诉你如何禁用它。

@bot.command()
@commands.guild_only()
async def example(ctx):
#do things

最新更新