创建一个不和谐机器人并希望从位于 cog 文件夹的特定 .py 文件中的 .json 文件加载数据

问题描述 投票:0回答:1

我正在创建一个 python discord 机器人并卡在加载数据上。 我的文件夹结构是这样的

|Bot folder
|-Cogs
|--ping.py
|-Data Storage
|--.env
|--channel.json
|-main.py

以下是我用于文件的代码:- 主要.py

#MODULES
import os
import asyncio
import discord
from dotenv import load_dotenv
from discord.ext import commands

#LOADING ENVIORMENT FILE
load_dotenv(dotenv_path = os.path.join(os.path.dirname(__file__), 'Data Storage', '.env'))

#ACCESSING BOT TOKEN
Token = os.getenv('BOT_TOKEN')

#DEFINING INTENTS
intents = discord.Intents.all()

#BOT PREFIX
bot = commands.Bot(command_prefix = '!', intents = intents)

#MAIN CODE

# (1) Loading Cog's.
async def load():
    cog_dir = os.path.join(os.path.dirname(__file__), 'Cogs')
    for filename in os.listdir(cog_dir):
        if filename.endswith('.py'):
            await bot.load_extension(f'Cogs.{filename[:-3]}')

# () Running the Bot.
async def main():
    await load()
    await bot.start(Token)

asyncio.run(main())

ping.py(要修改这个文件)

#MODULES
import os
import discord
from discord.ext import commands

#DEFINING INTENTS
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = '!', intents = intents)

#MAIN CODE
class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print('|---------------------------------------------------->')
        print(f' #{self.bot.user.name} has invaded the server...')
        print(f' Bot Id: {self.bot.user.id}')
        print('|---------------------------------------------------->')
        print('     ')

async def setup(bot):
    await bot.add_cog(Ping(bot))

频道.json

{
    "BOT_CHANNEL_ID": "1196004195292164136"
}

在 ping.py 中,我想从 channel.json (BOT_CHANNEL_ID) 加载数据,以便我可以在该通道中发送嵌入消息,让机器人上线并准备使用。

我尝试像这样在 ping.py 中编写代码,但它不起作用。

import os
import discord
from discord.ext import commands
import json

class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print('Bot is online!')

        # Load the channel ID from the JSON file
        channel_id = await self.load_channel_id()
        print(f'Loaded channel ID: {channel_id}')

        # Get the channel object
        channel = self.bot.get_channel(int(channel_id))
        print(f'Found channel: {channel}')

        if channel:
            # Send a message to the specified channel
            await channel.send('Bot is online!')

    async def load_channel_id(self):
        # Load the entire JSON file
        json_file_path = os.path.join(os.path.dirname(__file__), 'Data Storage', 'channel.json')

        with open(json_file_path, 'r') as file:
            data = json.load(file)

        # Fetch the desired channel ID
        return data.get("BOT_CHANNEL_ID", None)

async def setup(bot):
    await bot.add_cog(Ping(bot))

机器人确实已上线,但未在指定频道发送消息。此外,它不会在终端中给出任何错误消息。我尝试使用 try: 和 except: 但它也没有给出错误消息。所以,我很困惑。正在寻找有关此主题的帮助。预先感谢。

python python-3.x discord.py
1个回答
0
投票

os.path.dirname(__file__)
将返回
ping.py
所在文件夹的文件路径,
Bot folder/Cogs

使用

os.path.join
,文件路径将为
Bot folder/Cogs/Data Storage/channel.json
,这不是您要查找的文件路径;
Bot folder/Data Storage/channel.json

因此,

load_channel_id
将返回 None,并且
if channel
将防止发生任何错误。

您所要做的就是删除

os.path.dirname(__file__)
,因为它不是您想要的文件路径。

json_file_path = os.path.join('Data Storage', 'channel.json')

下次调试时,您可以尝试使用

print
语句来检查在这种情况下文件路径是否正确。

© www.soinside.com 2019 - 2024. All rights reserved.