允许机器人命令(仅用于测试)

时间:2021-03-03 15:11:31

标签: python discord discord.py pytest

我想使用 pytest 为我的应用程序创建一个简单的烟雾测试。这对我来说真的很简单,这就是我尝试的原因。问题是机器人不会像我注意到的那样对其他机器人的消息做出反应。我查看了代码 (bot.py) 并修改了 process_commands 仅用于冒烟测试。不幸的是,它仍然只适用于测试期间的人工消息。

修改代码,完整测试(只导入HASH和channel id)

from discord.ext import commands
import pytest
import threading
import time

from build_config import HASH, channel_id


bot = commands.Bot(command_prefix = '.', description="This is a test bot for stackoverflow!")


class Test_Message(commands.Cog):
    @commands.command(pass_context = True)
    async def message(self, ctx):
        await ctx.send("text_message")


def run_bot():
    bot.add_cog(Test_Message())
    bot.run(HASH.DEBUG)


@pytest.fixture
def create_bot():
    t1 = threading.Thread(target=run_bot, args=[])
    t1.start()


class Test_Events:
    successful = False

    @staticmethod
    @bot.event
    async def on_ready():
        channel = bot.get_channel(channel_id)
        await channel.send('.message')

    @staticmethod
    @bot.event
    async def on_message(message):
        await bot.process_commands(message)
        if (message.channel.name == "general" and message.clean_content == "text_message"):
            Test_Events.successful = True

    @staticmethod
    @bot.event
    async def process_commands(message):
        ctx = await bot.get_context(message)
        await bot.invoke(ctx)


@pytest.mark.asyncio
async def test_Smoke(create_bot):
    must_end = time.time() + 60
    while time.time() < must_end:
        if Test_Events.successful:
            break
        time.sleep(1)
    assert Test_Events.successful

基本上有人在 Allow Discord Rewrite bot to respond to other bots 中将此标记为解决方案,但它对我不起作用。

编辑:所以我调试了 discord.py,不幸的是,get_context self._skip_check(message.author.id, self.user.id) 中至少还有另一个检查。

1 个答案:

答案 0 :(得分:0)

所以结果是 discord.py 的创建者创建了一个可覆盖的 process_commands 函数。这就是为什么你可以删除

if message.author.bot:
    return

部分。不幸的是,这对任何事情都不够,代码中有这么一段拒绝机器人命令:

if self._skip_check(message.author.id, self.user.id):
    return ctx

解决方案是取消此检查:

bot._skip_check = lambda x, y: False

我只使用这个解决方法进行测试,禁止在普通服务器上使用类似的方法。