首页 > 解决方案 > 如何从 Discord.py 中的循环事件发送 DM

问题描述

尝试向用户发送 PM 但没有任何效果:

async def main_loop():
    await bot.wait_until_ready()
    while not bot.is_closed():
        # do stuff...
        if some_random_condition:
            user = bot.get_user(user_id)
            user.send_message("some message")  # doesn't work, user is Nonetype, id is correct though

bot.loop.create_task(main_loop())
bot.run(DISCORD_TOKEN)

由于这只是一个循环函数,我并没有通过 discord.py 框架传入的上下文或消息对象,我只有机器人 - 但我不知道如何使用机器人来访问用户给他们发一个 PM。

标签: python-3.xbotsdiscord.py

解决方案


假设您根据您的评论获得了正确的 ID,这就是您必须做的:

async def main_loop():
    await bot.wait_until_ready()
    while not bot.is_closed():
        # do stuff...
        if some_random_condition:
            user = await bot.fetch_user(user_id)
            await user.send("some message")

bot.loop.create_task(main_loop())
bot.run(DISCORD_TOKEN)


推荐阅读