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

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

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

ファイルとは、文字列に基づいた名前又はパスからアクセスすることができる、任意の情報のブロック又は情報を格納するためのリソースです。

Discord

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

GitHub

GitHubは、Gitバージョン管理システムを利用したソフトウェア開発向けの共有ウェブサービスです。GitHub商用プランおよびオープンソースプロジェクト向けの無料アカウントを提供しています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

1582閲覧

discord.py ファイルを2つ(cog)読み込む方法

Libe

総合スコア13

ファイル

ファイルとは、文字列に基づいた名前又はパスからアクセスすることができる、任意の情報のブロック又は情報を格納するためのリソースです。

Discord

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

GitHub

GitHubは、Gitバージョン管理システムを利用したソフトウェア開発向けの共有ウェブサービスです。GitHub商用プランおよびオープンソースプロジェクト向けの無料アカウントを提供しています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/10/09 06:02

編集2021/10/09 06:06

やりたいこと
cogファイルを2つにして読み込みたい
理由
1個のファイルがコードかんりがむずかしくなったから

ファイル構成

Github | |--cogs | |--LibeCog2.py | LibeCog.py | main.py

main.py

python

1from discord.ext import commands 2import traceback 3 4from datetime import datetime, timedelta 5import datetime 6 7INITIAL_EXTENSIONS = ['cogs.LibeCog'] 8 9now = datetime.datetime.now() 10 11# コグとして用いるクラスを定義。 12 13 14class LibeBot(commands.Bot): 15 def __init__(self, command_prefix): 16 # スーパークラスのコンストラクタに値を渡して実行。 17 super().__init__(command_prefix) 18 19 # INITIAL_COGSに格納されている名前から、コグを読み込む。 20 # エラーが発生した場合は、エラー内容を表示。 21 for cog in INITIAL_EXTENSIONS: 22 try: 23 self.load_extension(cog) 24 except Exception: 25 traceback.print_exc() 26 27 28 async def on_ready(self): 29 print('--------------------------------------') 30 print('Logged on as {0}!'.format(self.user)) 31 print('-------------------------------------') 32 print(self.user.name) 33 print('--------------------------------------') 34 print(self.user.id) 35 print('-------------------------------------') 36 print('ログインしました。') 37 print('-------------------------------------') 38 print(now.date()) 39 print('--------------------------------------') 40 41 42 43 44if __name__ == '__main__': 45 bot = LibeBot(command_prefix='.') 46 bot.run('TOKEN') 47

LIbeCog.py

python

1import discord 2import logging 3import abc 4import requests 5from discord.ext import tasks, commands 6import aiohttp 7from pprint import pprint 8import asyncio 9import json 10import typing 11import traceback 12import random 13import time 14import re 15from discord.ext import commands 16from datetime import datetime, timedelta 17import datetime 18import sys 19from pytz import timezone 20import socket 21 22 23time_sta = time.time() 24 25now = datetime.datetime.now() 26 27intents = discord.Intents.all() 28 29CHANNEL_ID = 845440592258662433 30 31host = socket.gethostname() 32print('--------------------------------------------------') 33print(host) 34 35# ipアドレスを取得、表示 36ip = socket.gethostbyname(host) 37print('--------------------------------------------------') 38print("IPアドレス",ip) 39print('--------------------------------------------------') 40 41# コグとして用いるクラスを定義。 42class LibeCog(commands.Cog): 43 44 @commands.command() 45 async def k(self, ctx): 46 async with ctx.typing(): 47 await asyncio.sleep(4) 48 await ctx.send("https://c.tenor.com/Jt0VfYbpyAoAAAAC/%E3%82%AD%E3%82%BA%E3%83%8A%E3%82%A2%E3%82%A4-kizuna-ai.gif") 49 print("年",now.year,"月",now.month,"日",now.day,) 50 51 @commands.command() 52 async def typing(self, ctx): 53 async with ctx.typing(): # 送られてきたチャンネルで入力中と表示させる 54 await asyncio.sleep(3) # 重い処理をwith内で書く。(一例) 55 await ctx.send("?") 56 57 @commands.command() 58 async def gg(self, ctx): 59 await ctx.send("https://storage.googleapis.com/support-forums-api/attachment/message-119416521-7110180789076656037.gif") 60 61 @commands.command() 62 async def bbf(self, ctx): 63 await ctx.send("https://thumbs.gfycat.com/AcademicAffectionateFoal-size_restricted.gif") 64 65 @commands.command() 66 async def hiroyuki(self, ctx): 67 await ctx.send("http://livedoor.blogimg.jp/source_2ch/imgs/9/7/971eec30.gif") 68 69 @commands.command() 70 async def hiroyuki1(self, ctx): 71 await ctx.send("https://up.gc-img.net/post_img/2021/06/p4JCYlTEdYbcpMF_S3lMY_193.gif") 72 73 74 75 @commands.Cog.listener() 76 async def on_message(self, message): 77 78 print('メッセージが来たよ→ {0.author}: {0.content}'.format(message)) 79 80 81 82 if message.content.startswith('/id'): 83 await message.channel.send('PaL_Libe') 84 85 if message.content == '!bot': 86 await message.channel.send('```BOT discordバージョン起動中です。```') 87 88 if message.content.startswith('Hi'): 89 await message.channel.send(message.author.mention + 'こんちゃーす') 90 91 if message.content.startswith('/nhk'): 92 await message.channel.send( 93 message.author.mention + 94 'https://gendai.ismedia.jp/mwimgs/2/7/-/img_27d1ecc00191cbbf4d98e1129f2399f544134.jpg' 95 ) 96 97 if message.content.startswith('/2'): 98 await message.channel.send( 99 message.author.mention + 100 'https://img.huffingtonpost.com/asset/5c6389752300007601224077.jpeg?ops=1200_630' 101 ) 102 103 104 if message.content.startswith('/日にち'): 105 await message.channel.send(f"```{now.date()}です。```") 106 107 if message.content.startswith('/clean'): 108 await message.channel.purge() 109 await message.channel.send('????✡????????☼✡⚐????????✋????✌????✋❄✌') 110 111 if message.channel.id != CHANNEL_ID: # チャンネルが違う場合は無視する 112 return 113 114 if message.content == '/qa': 115 await message.channel.send('l') 116 await asyncio.sleep(3) 117 await message.channel.send('情報漏洩防止のため10秒で削除します') 118 await asyncio.sleep(10) 119 await message.channel.purge() 120 121 122time_end = time.perf_counter() 123tim = time_end- time_sta 124 125def setup(bot): 126 print(tim) 127 print('--------------------------------------------------') 128 print('LibeCogファイルを読み込んだよ!') 129 bot.add_cog(LibeCog(bot)) 130

LibeCog2.py

python

1from discord.ext import tasks, commands 2 3class LibeCog2(commands.Cog): 4 5 @commands.command() 6 async def ffgb(self, ctx): 7 async with ctx.typing(): # 送られてきたチャンネルで入力中と表示させる 8 await asyncio.sleep(3) # 重い処理をwith内で書く。(一例) 9 await ctx.send("?") 10 11 12 13 @commands.Cog.listener() 14 async def on_message(self, message): 15 16 17def setup(bot): 18 print('--------------------------------------------------') 19 print('LibeCog2ファイルを読み込んだよ!') 20 bot.add_cog(LibeCog2(bot))

開発環境

python-3.9.5 discord.py==1.7.3

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

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

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

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

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

guest

回答1

0

ベストアンサー

main.py

1INITIAL_EXTENSIONS = ['cogs.LibeCog','cogs.LibeCog2']

main.pyのINITIAL_EXTENSIONSをこう書くと良いと思います。

投稿2021/10/09 06:17

kntm

総合スコア58

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

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

Libe

2021/10/09 06:24

試したらエラーコードが出ました
Libe

2021/10/09 06:24

Traceback (most recent call last): 2021-10-09T06:23:16.776467+00:00 app[discordbot.1]: File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec 2021-10-09T06:23:16.776467+00:00 app[discordbot.1]: spec.loader.exec_module(lib) 2021-10-09T06:23:16.776472+00:00 app[discordbot.1]: File "<frozen importlib._bootstrap_external>", line 851, in exec_module 2021-10-09T06:23:16.776472+00:00 app[discordbot.1]: File "<frozen importlib._bootstrap_external>", line 988, in get_code 2021-10-09T06:23:16.776474+00:00 app[discordbot.1]: File "<frozen importlib._bootstrap_external>", line 918, in source_to_code 2021-10-09T06:23:16.776487+00:00 app[discordbot.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-10-09T06:23:16.776505+00:00 app[discordbot.1]: File "/app/cogs/LibeCog2.py", line 74 2021-10-09T06:23:16.776526+00:00 app[discordbot.1]: def setup(bot): 2021-10-09T06:23:16.776528+00:00 app[discordbot.1]: IndentationError: expected an indented block 2021-10-09T06:23:16.776544+00:00 app[discordbot.1]: 2021-10-09T06:23:16.776544+00:00 app[discordbot.1]: The above exception was the direct cause of the following exception: 2021-10-09T06:23:16.776544+00:00 app[discordbot.1]: 2021-10-09T06:23:16.776545+00:00 app[discordbot.1]: Traceback (most recent call last): 2021-10-09T06:23:16.776561+00:00 app[discordbot.1]: File "/app/main.py", line 23, in __init__ 2021-10-09T06:23:16.776562+00:00 app[discordbot.1]: self.load_extension(cog) 2021-10-09T06:23:16.776564+00:00 app[discordbot.1]: File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 678, in load_extension 2021-10-09T06:23:16.776564+00:00 app[discordbot.1]: self._load_from_module_spec(spec, name) 2021-10-09T06:23:16.776576+00:00 app[discordbot.1]: File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec 2021-10-09T06:23:16.776577+00:00 app[discordbot.1]: raise errors.ExtensionFailed(key, e) from e 2021-10-09T06:23:16.776599+00:00 app[discordbot.1]: discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.LibeCog2' raised an error: IndentationError: expected an indented block (LibeCog2.py, line 74)
Libe

2021/10/09 06:28

LibeCog2.pyに適当に反応させるコード書いたら反応しました
kntm

2021/10/09 06:32

エラーを読む限りは74行目のインデントが正しくないようです
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問