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

时间:2021-01-04 07:57:59

标签: python discord bots discord.py

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

例如:

 if message.content == '!Hello':
 await message.channel.send('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 不是不同的。我的问题是如何确保“频道”属性根据调用它的服务器而变化。我想要它,所以如果我说 !Hello 在我的测试服务器中,它不会发送到主服务器,只发送到测试服务器。

似乎是一个非常微不足道的答案,但我只是在努力寻找它,感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用消息的 .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

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

目前的处事方法会导致相当多的重复代码。

我还建议查看 discord 的命令扩展,而不是为它们使用 on_message 事件。


参考: