質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
Discord

Discordは、ゲーマー向けのボイスチャットアプリです。チャット・通話がブラウザ上で利用可能で、個人専用サーバーも開設できます。通話中でも音楽を流したり、PC画面を共有できるなど多機能な点が特徴です。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

3回答

2470閲覧

discord.pyにおいてCogとAppCommandを両方使う

Ray_

総合スコア12

Discord

Discordは、ゲーマー向けのボイスチャットアプリです。チャット・通話がブラウザ上で利用可能で、個人専用サーバーも開設できます。通話中でも音楽を流したり、PC画面を共有できるなど多機能な点が特徴です。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2022/11/29 08:20

環境

Python 3.9.13, discord.py 2.1.0

実現したいこと

discord.pyにおいてCogとスラッシュコマンドの両方を同時に使いたいです

発生している問題・エラーメッセージ

python

1# Botのprefixを$<コマンド>として登録しています 2# /hoge とするとエラーメッセージ等無し 3# $hoge とすると 4discord.ext.commands.errors.CommandNotFound: Command "hoge" is not found 5# Cogを読み込んでいないということはありません

該当のソースコード

main.py内のsetup_hookの記述
これ以外にapp_commandsにかかわる記述はしていません

python

1async def setup_hook(self) -> None: 2 for extension in DiscordBot.cogs: 3 try: 4 await self.load_extension(extension) 5 except Exception as e: 6 print('Could not load extension {0} due to {1.__class__.__name__}: {1}'.format( 7 extension, e)) 8 await self.tree.sync()

スラッシュコマンド化したいコマンドの入ったCogの記述

python

1import discord 2from discord import app_commands 3from discord.ext import commands 4 5class MyCog(commands.Cog): 6 def __init__(self, bot: commands.Bot) -> None: 7 self.bot = bot 8 9 @app_commands.command() 10 async def hoge(self, interaction: discord.Interaction): 11 """Says hello!""" 12 await interaction.response.send_message(f'Hi, {interaction.user.mention}') 13 14 15async def setup(bot: commands.Bot) -> None: 16 await bot.add_cog(MyCog(bot))

試したこと

main.py内に直接

python

1@bot.tree.command() 2async def hello(interaction: discord.Interaction): 3 """Says hello!""" 4 await interaction.response.send_message(f'Hi, {interaction.user.mention}')

と記述することで、スラッシュコマンドに登録されていました

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答3

0

動作している私の例です。

python

1class MyBot(commands.Bot): 2 async def setup_hook(self): 3 for filename in os.listdir("./cogs"): 4 if filename.endswith(".py"): 5 await bot.load_extension(f"cogs.{filename[:-3]}") 6 7 async def on_ready(self): 8 print("BOT起動") 9 await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name ="Youtube")) 10 await bot.tree.sync() 11 12bot = MyBot(command_prefix = "gaming!",intents=discord.Intents.all(),help_command= None)

まずここでの違う点は
self.load_extentionではなくbot.load_extentionですね

Cog

python

1class mod(commands.Cog): 2 def __init__(self,bot): 3 self.bot = bot 4 5 @app_commands.command() 6 async def hoge(self, interaction: discord.Interaction): 7 """Says hello!""" 8 await interaction.response.send_message(f'Hi, {interaction.user.mention}') 9 10async def setup(bot): 11 await bot.add_cog(mod(bot))

こうですね

あとCogが読み込まれたか確認するために
Cog内に

python

1@commands.Cog.listener() 2async def on_ready(self) 3 print("Cogロード完了")

と入力するといいですよ!
それで私は確認しています。

投稿2022/12/20 00:14

Act_Celery

総合スコア20

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Ray_

2022/12/27 17:50

お返事ありがとうございます。そして返信が遅くなり本当に申し訳ありません。 一部しか切り取らずに貼ったせいですね...。 ```python class Mybot(commands.Bot): def __init__(self, **kwargs): intents = discord.Intents.all() super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents, **kwargs, pm_help=None, help_attrs=dict(hidden=True)) async def setup_hook(self) -> None: self.add_view(streaming.StreamingManagementPanel()) for extension in DiscordBot.cogs: try: await self.load_extension(extension) except Exception as e: print('Could not load extension {0} due to {1.__class__.__name__}: {1}'.format( extension, e)) await self.tree.sync() bot = Mybot() ``` 現状このようにインスタンスをはやして処理しているため、ここでの`load_extentions`の頭は`self`で大丈夫なんです...。(現状その他のコグは読み込まれているので) `main.py`内で改めて`self.tree`をオーバーライドすることで解決しました...!お返事ありがとうございます! 改めて返信が遅くなり本当に申し訳ありませんでした。
guest

0

Cogにしたからといってメッセージコマンドが登録されるわけがありません。

python

1 @app_commands.command() 2 async def hoge(self, interaction: discord.Interaction): 3 """Says hello!""" 4 await interaction.response.send_message(f'Hi, {interaction.user.mention}')

を、

python

1 @commands.hybrid_command() 2 async def hoge(self, ctx: commands.Context): 3 """Says hello!""" 4 await ctx.send(f'Hi, {ctx.author.mention}')

のように、ハイブリッドコマンドを使って書き換えを行うと解決するはずです。

投稿2022/12/15 06:25

yaakiyu

総合スコア124

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Ray_

2022/12/27 17:40

お返事ありがとうございます。そして返信がとても遅くなり本当に申し訳ありません。 hybrid_commandのお話を初めて聞きました!たった今APIで確認してこちらの方が便利そうでしたので早速変更させていただきます!ありがとうございます! そして返信が遅くなり本当に申し訳ありませんでした。
guest

0

ベストアンサー

自分はdpyユーザーじゃないので絶対こうとは言い切れませんが。。


py

1async def setup_hook(self) -> None: 2 for extension in DiscordBot.cogs: 3 try: 4 await self.load_extension(extension) 5 except Exception as e: 6 print('Could not load extension {0} due to {1.__class__.__name__}: {1}'.format( 7 extension, e)) 8 tree = await self.tree.sync() 9 print(tree)

でsync()の返り値をプリントしてみてください。

あと、おそらくself.treeを__init__() 内で上書きしてみてください。
ここが気になるんですよね・・。

py

1self.tree = app_commands.CommandTree(self)

投稿2022/12/05 02:26

pecop

総合スコア409

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Ray_

2022/12/27 17:37

本当に返信が遅くなって大変申し訳ありません。 ```py [<AppCommand id=1057350211015561278 name='hoge' type=<AppCommandType.chat_input: 1>>] ``` ご指摘の通り, オーバーライドすることで解決しました!こんなにも早くご教授いただいたのにもかかわらず返信遅くなり本当に申し訳ありません。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問