首页 文章

on_message不会检测到任何消息

提问于
浏览
1

我正在用discord.py写一个discord bot . 我写了一个初始版本,但我认为这一切都需要重组,所以我将代码移动到不同的文件 .

代码与之前的代码完全相同,但现在当我启动机器人时,机器人检测到没有消息在任何服务器中发送,除非消息来自机器人本身 .

处理 client 的主要代码是:

import discord
import time
from command_list import *
from resource_functions import grab_setting_from_category

print("Main initialized")

client = discord.Client()
token = "BOT TOKEN"

prefix = "!"


@client.event
async def on_ready():
    print("*** BOT IS READY ***")

    async def server_count_loop():
        while True:
            servers = client.servers
            await client.change_presence(
                game=discord.Game(name=" in {0} Servers".format(str(len(servers)))))
            time.sleep(10)

        for server in client.servers:
            for channel in server.channels:
                if channel.name == "general":
                    await client.send_message(channel, content="Bot Online")

    await server_count_loop()


@client.event
async def on_message(message):
    print("Message detected from {0} as '{1}'".format(message.author, message.content))
    if not message.author.bot:
        global prefix
        prefix = grab_setting_from_category(message.server.id, "server", "prefix")
        if message.content.startswith(prefix):
            for i in range(0,len(commands)):
                key = list(commands.keys())[i]
                table = list(commands.values())[i]
                if message.content.startswith(prefix+key):
                    table["function"](message, commands)


client.run(token)

在代码中,在 on_message 函数的开头有 print(...) ,我正在使用它作为一种基本方法让我知道机器人是否正在检测消息 . 每当机器人在 on_ready 中发送消息时,print语句就会打印,但Discord上其他用户的消息都没有触发该功能 .

1 回答

  • 2

    不要使用:

    time.sleep(...)
    

    相反,使用:

    await asyncio.sleep(...)
    

    time.sleep 是一个阻塞调用,它会阻止asyncio循环继续运行 . 这就是为什么你需要一个异步 .sleep(...) 方法 .

相关问题