允许bot命令(仅用于测试)



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

编辑代码,完整的测试(只导入HASH和通道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

基本上有人标记这一个作为一个解决方案在允许不和谐重写机器人响应其他机器人,但它不适合我。

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

所以原来是discord.py的创建者创建了一个可重写的process_commands函数。这就是为什么你可以去掉

if message.author.bot:
return

部分。不幸的是,这还不够,在代码深处有这样一个部分拒绝bot命令:

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

解决办法是把这张支票拿出来:

bot._skip_check = lambda x, y: False

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

最新更新