実現したいこと
自作discord botでボイスチャンネルの接続、切断をできるようにする。
発生している問題・分からないこと
botを起動し、discord側で接続コマンドを実施して接続。その後切断コマンドを実行したところ、エラーが発生。
connect実行時にvoiceChannelに値が入っていないように見えましたが解決できません。
また、connect関数の最後のprint結果(connect end)が出力されていません。
エラーメッセージ
error
1Ignoring exception in command disconnect: 2Traceback (most recent call last): 3 File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 85, in wrapped 4 ret = await coro(*args, **kwargs) 5 File "/opt/discord_bot/discord_bot.py", line 37, in disconnect 6 voiceChannel.stop() 7NameError: name 'voiceChannel' is not defined 8 9The above exception was the direct cause of the following exception: 10 11Traceback (most recent call last): 12 File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 939, in invoke 13 await ctx.command.invoke(ctx) 14 File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 863, in invoke 15 await injected(*ctx.args, **ctx.kwargs) 16 File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 94, in wrapped 17 raise CommandInvokeError(exc) from exc 18discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'voiceChannel' is not defined
該当のソースコード
discord_bot.py
1from discord.ext import commands 2import discord 3from discord.channel import VoiceChannel 4 5TOKEN = 'MY_TOKEN' 6bot = commands.Bot( 7 command_prefix="!" 8 ) 9voiceChannel: VoiceChannel 10 11 12@bot.event 13async def on_ready(): 14 print('on_ready') 15 16#--------------------------------------------------------------- 17#ボイスチャンネルに接続 18#--------------------------------------------------------------- 19@bot.command() 20async def connect(ctx): 21 global voiceChannel 22 print('connect start') 23 24 voiceChannel = await VoiceChannel.connect(ctx.author.voice.channel) 25 26 print('connect end') 27 return 28 29#--------------------------------------------------------------- 30#ボイスチャンネルから切断 31#--------------------------------------------------------------- 32@bot.command() 33async def disconnect(ctx): 34 global voiceChannel 35 print('disconnect start') 36 37 voiceChannel.stop() 38 await voiceChannel.disconnect() 39 #await ctx.voice_client.disconnect() 40 41 print('disconnect end') 42 return 43 44 45bot.run(TOKEN)
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
disconnect関数を以下のように変えると、エラーは発生しないが切断ができない状態となります。
disconnect
1async def disconnect(ctx): 2 global voiceChannel 3 print('disconnect start') 4 5 #voiceChannel.stop() 6 #await voiceChannel.disconnect() 7 await ctx.voice_client.disconnect() 8 9 print('disconnect end') 10 return
また、ソースコード9行目に宣言しているvoiceChannelの型をVoiceClientに変更しても同様にdisconnect内でvoiceChannelの定義がされていない旨のエラーが発生します。
補足
以下環境で実施。
- Raspbian GNU/Linux 10 (buster)
- Python 3.7.3
- discord.py 1.7.3
以下参考にしました。
公式APIリファレンス
コード作成時の参考1
コード作成時の参考2

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。