【问题标题】:Why is my discord bot repeating the on_ready function endlessly为什么我的不和谐机器人无休止地重复 on_ready 功能
【发布时间】:2022-01-03 02:06:06
【问题描述】:

我正在为 discord 编写一个机器人,而我的 on_ready 函数在我用 PostgreSQL 重写之后不断重复。这是我的代码:

@bot.event
async def on_ready():
    """The on_ready function is executed when the bot starts and creates the users table in the database, also adds names, id, the number of xp and the server of all participants that are not in the database to the database.
    """
    DiscordComponents(bot)
    cursor.execute("""CREATE TABLE IF NOT EXISTS users (
        name VARCHAR(255), 
        id BIGSERIAL PRIMARY KEY, 
        xp INT
    );""")
    for guild in bot.guilds:
        for member in guild.members:
            if member.id not in bots:
                try:
                    cursor.execute("""INSERT INTO users VALUES ('{}', {}, {});""".format(member, member.id, 0))
                except:
                    continue
    connect.commit()
    print("Bot connected!")

为什么会发生这种情况以及如何纠正它以及为什么此函数不向数据库中添加数据?

【问题讨论】:

  • 您阅读文档了吗? This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.

标签: python postgresql discord.py


【解决方案1】:

on_ready 事件可以多次调用,因为机器人可以重新连接到 Discord。所以,我建议你写这样的东西:

from discord.ext import commands
from discord.ext import tasks


bot = commands.Bot(command_prefix="!")

@tasks.loop(count=1)
async def wait_until_ready():
    await bot.wait_until_ready()
    # update your database and do whatever here

wait_until_ready.start()
bot.run('token')

那么您将只在第一个on_ready 事件之后更新数据库一次。

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2020-05-11
    • 2021-02-01
    • 2018-02-25
    • 2021-08-03
    • 2021-07-30
    相关资源
    最近更新 更多