【问题标题】:Discord.py running an async function on demandDiscord.py 按需运行异步函数
【发布时间】:2020-10-28 20:34:05
【问题描述】:

我想在某个时间运行以下异步函数。

async def test(ctx):
    channel = bot.get_channel(730099302130516058)
    await channel.send('hello')

我正在测试它 asyncio.run(test(bot.get_context))。但是当我运行它时,我得到'NoneType' object has no attribute 'send' 并且我已经对此进行了测试,这意味着通道等于无,因此它无法将消息作为通道=“无”发送。

现在,当我执行以下操作时,它可以工作。但当然我必须运行命令 test

@bot.command()
async def test(ctx):
    channel = bot.get_channel(730099302130516058)
    await channel.send('hello')

我计划在我需要的时候使用 schedule 来运行它,但仍会以类似的方式调用该函数。 有没有办法调用异步函数并正确传递 ctx?

完整代码:

import discord
from discord.ext import commands
import asyncio

TOKEN = "Token Would Be Here"
bot = commands.Bot(command_prefix='+')

async def test(ctx):
    channel = bot.get_channel(730099302130516058)
    await channel.send('hello')

asyncio.run(test(bot.get_context))
bot.run(TOKEN)

【问题讨论】:

  • 您可以编辑您的问题以包含您的其余代码吗?理想情况下,minimal, reproducible example。调用 bot.get_channel 时,似乎未连接机器人,导致返回 None
  • @Benjin 我已经添加了其余的代码。您应该能够看到机器人已连接。谢谢

标签: python-3.x discord.py


【解决方案1】:

bot.get_channel() 正在返回 None,因为机器人尚未连接,这意味着它看不到任何频道。您需要添加await bot.wait_until_ready(),这将强制机器人等待连接,然后再继续。

您也不需要传递ctx,因为您从不使用它。

discord.py 也已经拥有自己的事件循环供您使用。您可以使用 bot.loop.create_task() 将协程添加到循环中。

from discord.ext import commands

TOKEN = "Token Would Be Here"
bot = commands.Bot(command_prefix='+')

async def test():
    await bot.wait_until_ready()
    channel = bot.get_channel(370935329353367568)
    await channel.send('hello')

bot.loop.create_task(test())
bot.run(TOKEN)

【讨论】:

    猜你喜欢
    • 2021-11-14
    • 2021-09-23
    • 2022-11-16
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多