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

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

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

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

Python 3.x

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

Q&A

解決済

2回答

3760閲覧

discord.pyのclient.runについて

miki_io

総合スコア1

Discord

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

Python 3.x

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

0グッド

0クリップ

投稿2022/10/19 07:31

前提

pythonでdiscord.pyを使用し,チャットbotを作ろうとしています
オウム返しの機能を実装中に以下のエラーメッセージが発生しました。

実現したいこと

botを起動させてオウム返しができるようにする

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

RuntimeError Traceback (most recent call last) Cell In [1], line 22 19 if message.content.startswith('$hello'): 20 await message.channel.send('Hello!') ---> 22 client.run('MTAyNzIwNjEzMzk5MzE4NTM1MA.GnWQZv.kkA4Nu6QBYfChqyB029HjwosaCZPDLxu0c-wCA') File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:828, in Client.run(self, token, reconnect, log_handler, log_formatter, log_level, root_logger) 820 utils.setup_logging( 821 handler=log_handler, 822 formatter=log_formatter, 823 level=log_level, 824 root=root_logger, 825 ) 827 try: --> 828 asyncio.run(runner()) 829 except KeyboardInterrupt: 830 # nothing to do here 831 # `asyncio.run` handles the loop cleanup 832 # and `self.start` closes all sockets and the HTTPClient instance. 833 return File ~\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py:33, in run(main, debug) 9 """Execute the coroutine and return the result. 10 11 This function runs the passed coroutine, taking care of (...) 30 asyncio.run(main()) 31 """ 32 if events._get_running_loop() is not None: ---> 33 raise RuntimeError( 34 "asyncio.run() cannot be called from a running event loop") 36 if not coroutines.iscoroutine(main): 37 raise ValueError("a coroutine was expected, got {!r}".format(main)) RuntimeError: asyncio.run() cannot be called from a running event loop

該当のソースコード

python

1# This example requires the 'message_content' intent. 2 3import discord 4 5intents = discord.Intents.default() 6intents.message_content = True 7 8client = discord.Client(intents=intents) 9 10@client.event 11async def on_ready(): 12 print(f'We have logged in as {client.user}') 13 14@client.event 15async def on_message(message): 16 if message.author == client.user: 17 return 18 19 if message.content.startswith('$hello'): 20 await message.channel.send('Hello!') 21 22client.run

試したこと

アプデの影響によりintent部分の変更は直したのですが,clientの部分の直し方がわかりません
asyncioやawaitを使用するそうなのですが上手くいきませんでした

補足情報(FW/ツールのバージョンなど)

python 3.10.5
jupyternotebook を使用

ここにより詳細な情報を記載してください。

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

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

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

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

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

isanacCitrus

2022/10/19 10:01

とりあえず。エラー分にトークン乗っちゃってるので消しましょう。
miki_io

2022/10/19 14:25

ご指摘ありがとうございます 一旦消してトークン変更しました!
guest

回答2

0

これトークン出てますよ
今すぐエラーメッセージ消しましょう

投稿2022/10/20 10:03

Act_Celery

総合スコア20

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

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

miki_io

2022/10/21 02:13

ご指摘ありがとうございます トークンのほうは消させていただきました
Act_Celery

2022/10/21 13:54

いやここの部分です エラーメッセージの最初のあたり client.run('MTAyNzIwNjEzMzk5MzE4NTM1MA.GnWQZv.kkA4Nu6QBYfChqyB029HjwosaCZPDLxu0c-wCA')
Act_Celery

2022/10/22 00:36

なのでリセットしたほうがいいかと思われます
miki_io

2022/10/22 14:20

消したをリセットの認識で使っていました ありがとうございます
guest

0

ベストアンサー

jupyternotebook を使用

python を通常通りローカルにインストールした環境等であれば問題なく動きます。
Jupyter Notebook で実行したときに「RuntimeError: asyncio.run() cannot be called from a running event loop」のエラーが起こるのは
Jupyter Notebook内でイベントループが走っている状態で、新たに discord ライブラリ内でイベントループを発生させようとするためです。

対策

すでに実行中のJupyter Notebookのイベントループを取得し、そのイベントループにクライアントを開始するコルーチンを投げるようにしてください。

Jupyter Notebookで動かす場合

python

1import discord 2import asyncio 3 4TOKEN = 'discordのトークン' 5 6loop = asyncio.get_event_loop() 7 8intents = discord.Intents.default() 9intents.message_content = True 10client = discord.Client(intents=intents) 11 12@client.event 13async def on_ready(): 14 print(f'We have logged in as {client.user}') 15 16@client.event 17async def on_message(message): 18 if message.author == client.user: 19 return 20 if message.content.startswith('$hello'): 21 await message.channel.send('Hello!') 22 23async def runner(): 24 try: 25 await client.start(TOKEN) 26 finally: 27 if not client.is_closed(): 28 await client.close() 29 30loop.create_task(runner(TOKEN))

参考:https://stackoverflow.com/questions/69767952/how-to-run-discord-py-interactively-in-jupyter-notebook

※python 3.8.6、discord 2.0.1、 vscode内にインストールしたipykernel7.70にて確認。


追記

Jupyter Notebookではない、通常のローカル環境に普通にインストールした Python 環境下で動かす場合:

import discord intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'We have logged in as {client.user}') @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') client.run('discordのトークン')

追記2

下記のエラーから、discord botの権限設定に問題があると考えられます。

line 672, in connect raise PrivilegedIntentsRequired(exc.shard_id) from None discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page.

訳:「672行目で、接続中 discord.errors.PrivilegedIntentsRequired 例外が None discord.errors.PrivilegedIntentsRequired から発生しています。Shard ID None は、開発者ポータルで明示的に有効化されていない特権的なインテントを要求しています。https://discord.com/developers/applications/ にアクセスし、アプリケーションのページ内で特権的なインテントを明示的に有効にすることが推奨されます」


このエラーを解消するには、BOT に intent の読み取り権限を付与する必要があると考えられます。
下記の手順をお試しください。

<具体的手順>
https://discord.com/developers/applications/ にアクセスします。
② ログインID、パスワードを求められた場合は、開発者のログインID、パスワードを入力します。
③ Applications で、権限付与したいアプリのアイコンをクリックします
イメージ説明
④ 左のペインの「Bot」をクリックし、右側を下の方までスクロールして
MESSAGE CONTENT INTENT の右下にあるスイッチをONにします。
イメージ説明

この手順を行った後、再度、上記の「追記」に書いたコードで、コマンドプロンプトから実行してみて下さい。

投稿2022/10/19 15:45

編集2022/10/21 14:26
退会済みユーザー

退会済みユーザー

総合スコア0

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

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

miki_io

2022/10/20 05:27

ご丁寧な回答ありがとうございます。 TypeError: runner() takes 0 positional arguments but 1 was given jupyter notebookをやめて,コマンドプロンプトで直接行うと上記のようなエラーがでて,調べたところ引数selfを受け取れとのことだったので,async def runner(self):としたら新たなエラーが発生しました 6: DeprecationWarning: There is no current event loop loop = asyncio.get_event_loop() お忙しいところ恐縮ですが確認して頂けると幸いです。
退会済みユーザー

退会済みユーザー

2022/10/20 10:14 編集

回答前半のコードは一応Jupyter Notebook上で実行した場合に動かすことを想定したもので、Jupyter Notebookを使わずにローカルに普通にインストールしたpythonでは動きません。 回答の後半に追記したコードを、コマンドプロンプト経由で(JupyterNotebook下ではなくローカルに普通にインストールしたpython下で)動かした場合、どのようなエラーが出るでしょうか。 なお、 「6:DeprecationWarning: There is no current event loop loop = asyncio.get_event_loop()」 というのはエラーではなく警告で、Jupyter Notebook実行下ではないから event loop がありません、と言っているだけです。ただし event loop がないため何も実行されず終わっています。
miki_io

2022/10/21 02:44

[2022-10-21 11:32:51] [INFO ] discord.client: logging in using static token Traceback (most recent call last): File "C:\Users\.ipython\hello.py", line 20, in <module> client.run('トークン') File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 828, in run asyncio.run(runner()) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run return loop.run_until_complete(main) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete return future.result() File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 817, in runner await self.start(token, reconnect=reconnect) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 746, in start await self.connect(reconnect=reconnect) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 672, in connect raise PrivilegedIntentsRequired(exc.shard_id) from None discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead. Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000016A95E8EA70> Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "C:\Users\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close self._loop.call_soon(self._call_connection_lost, None) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon self._check_closed() File "C:\Users\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed このようになりました また,いただいた前半のコードをjuoyter notebookのほうで実行下ところ以下のようになりました <Task pending name='Task-11' coro=<runner() running at C:\Users\af19063\AppData\Local\Temp\ipykernel_9324\3595356673.py:23>>
退会済みユーザー

退会済みユーザー

2022/10/21 14:28

ご確認ありがとうございます。 おそらく、discord から入力されたメッセージを読み取る権限がないために、強制的に落ちてしまっているのではないかと考えられます。 「追記2」に権限を設定する手順を記載しましたので、お試しください。 これでも解消しない場合や、すでにスイッチはonになっているにもかかわらずエラーが発生しているような場合は、改めてコメントいただければと思います。
miki_io

2022/10/22 14:36

追記2を試した結果、無事に実行できました! 何度もご丁寧に教えていただきありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問