Bot 未通过 on_ready 函数 [python] 在服务器中发送消息

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

首先,我提到了下面的代码 [主要.py]

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

#CUSTOM MODULES
from Features.log import ErrrorLogs

#LOADING CUSTOM MODULES
ErrrorLogs()

#LOADING CONFIG FILE FROM CONFIG FOLDER
def load_data(file_path):
    with open(file_path, 'r') as file:
        return json.load(file)
    
Config_Path = r'Config\config.json'

data = load_data(Config_Path)

#LOADING ENVIRONEMENT FILE
env_path = os.path.join(os.path.dirname(__file__), 'Config', '.env')
load_dotenv(dotenv_path = env_path)

#GETTING VARIABLES FROM CONFIG FOLDER
Token = os.getenv('BOT_TOKEN')

Bot_Channel = data['BOT_CHANNEL'] # Bot response channel id.
Welcome_Channel = data['WELCOME_CHANNEL'] # Welcome channel id.

Prefix = data['PREFIX'] # Bot prefix.

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

#BOT PREFIX
client = commands.Bot(command_prefix = Prefix, intents = intents)

#MAIN

#(1) Bot Goes Online Message.
@client.event
async def on_ready():
    print('|' + '-'*50 + '>')
    print(f' {client.user.name} has envaded the server...')
    print(' Bot Name:', client.user.name)
    print(' Bot ID:', client.user.id)
    print('|' + '-'*50 + '>')

    channel = client.get_channel(Bot_Channel)

    await channel.send('Example test')

#(2) Loading Cogs Folder.
async def load():
    for filename in os.listdir('./Cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'Cogs.{filename[:-3]}')

#(3) Loading All The Fucntions.
async def main():
    await load()
    await client.start(Token)

#RUNNING THE BOT
asyncio.run(main())

我在这部分有问题

#(1) Bot Goes Online Message.
@client.event
async def on_ready():
    print('|' + '-'*50 + '>')
    print(f' {client.user.name} has envaded the server...')
    print(' Bot Name:', client.user.name)
    print(' Bot ID:', client.user.id)
    print('|' + '-'*50 + '>')

    channel = client.get_channel(Bot_Channel)

    await channel.send('Example text')

机器人正在终端中打印消息,但现在在不和谐频道中发送消息,不知道为什么。它甚至没有给出任何错误。

我尝试从不同的文件[test.py]发送消息,就像这样

import discord
from discord.ext import commands
import json

intents = discord.Intents.all()

def load_data(file_path):
    with open(file_path, 'r') as file:
        return json.load(file)
    
Config_Path = r'Config\config.json'

data = load_data(Config_Path)

Bot_Channel = data['BOT_CHANNEL']
Welcome_Channel = data['WELCOME_CHANNEL']
Prefix = data['PREFIX']

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

@bot.event
async def on_ready():
    print('Bot is online)
    print('Bot_Channel: ' + Bot_Channel)
    print('Prefix: ' + Prefix)
    print('Welcome_Channel: ' + Welcome_Channel)

    channel = bot.get_channel(Bot_Channel)

    if channel:
        await channel.send("Hello, I'm ready!")
    else:
        print("Channel not found.")

bot.run('123456789')

这也是我的channel.json 文件

{
    "PREFIX": "!",
    "BOT_CHANNEL": "11967.......",
    "WELCOME_CHANNEL": "1196........"
}

此代码打印除在服务器通道中发送消息之外的所有内容。 现在我很困惑。我很感谢有关此主题的帮助。

我尝试探索该网站上的相关问题,但似乎没有任何效果。

请根据我提到的第一个代码告诉解决方案,因为我最初使用 asyncio.run(main()) [我认为使用 asyncio.run(main()) 在发送消息之前需要进行一些更改]

提前谢谢您。

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

在 main.py 文件中,我可以看到多个问题,例如只需将代码放在函数外部即可轻松完成齿轮的加载,因为这里不需要函数。要运行机器人,您应该使用

client.run
而不是
client.start

进行更改后,代码应如下所示:

for filename in os.listdir('./Cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'Cogs.{filename[:-3]}')


client.run(Token)

我认为这里的问题在于

client.get_channel
,因为 get_channel 依赖于缓存,并且由于您想在开始时获取频道,因此您必须使用
client.fetch_channel

代码应如下所示:

#(1) Bot Goes Online Message.
@client.event
async def on_ready():
    print('|' + '-'*50 + '>')
    print(f' {client.user.name} has envaded the server...')
    print(' Bot Name:', client.user.name)
    print(' Bot ID:', client.user.id)
    print('|' + '-'*50 + '>')

    channel = await client.fetch_channel(Bot_Channel)

    await channel.send('Example text')
© www.soinside.com 2019 - 2024. All rights reserved.