如何使discord.py bot发送到调用它的服务器?

2024-10-05 12:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个关于discord.py的问题。 我运行我的bot所在的两个独立服务器:测试服务器和主服务器。 问题是,当我在测试服务器中发送消息时,bot会将其消息发送到主服务器,而不会将其发送回调用命令的服务器(仅在函数中)

例如:

 if message.content == '!Hello':
 await message.channel.send('Hello there!')

如果我在测试服务器中键入上述内容,我的bot将在测试服务器中像它应该的那样响应“Hello there!”。但是,如果我尝试将此代码放入函数并调用它:

if message.content == "!Hello":
    await hellomessage()

async def hellomessage():
    channel = client.get_channel('Channel ID Here')
    await channel.send('Hello there!')

通道ID显然设置为特定服务器。因此,假设我将ID“1234”作为我的主服务器,ID“1111”作为我的测试服务器,无论我在测试服务器还是主服务器中调用它,该消息都将发送到主服务器,因为ID没有什么不同。我的问题是如何确保“channel”属性根据调用它的服务器而改变。如果我说的话,我希望如此!您好,在我的测试服务器中,它不发送到主服务器,只发送到测试服务器

似乎是一个非常琐碎的答案,但我只是在努力寻找它,任何帮助都是感激的


Tags: 函数服务器sendid消息messagehelloif
1条回答
网友
1楼 · 发布于 2024-10-05 12:27:38

您可以使用消息的.guild属性来检查发送了什么消息

例如:

# You can also have a separate coroutine for your main server
async def hello_test_message():
    test_guild_channel = client.get_channel(ID_HERE)
    await test_guild_channel.send("Hello there!")

@client.event
async def on_message(message):
    if client.user == message.author:
        return

    if message.guild.id == TEST_GUILD_ID_HERE:
        if message.content.lower() == "!hello":  # .lower() for case insensitivity
            await hello_test_message()
    # Another condition for your main server + calling the other coroutine

话虽如此,我假设您没有对每个可能通道的值等进行硬编码。如果是这种情况,并且您只希望bot在原始消息的通道中响应,您可以使用message.channel.send(...

当前的处理方法将导致相当多的重复代码

我还建议您研究一下discord的命令扩展,而不是为它们使用on_message事件


参考资料:

相关问题 更多 >

    热门问题