You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Discord Bot调用TIMER协程返回对象地址的问题

Discord Bot 定时器函数调用问题修复方案

问题根源

你直接将协程对象(stats_timer = TIMER()生成的实例)传给了send()方法,所以Bot返回了协程的内存地址;同时原TIMER()函数仅打印数字,没有实现发送消息到频道的逻辑,且循环存在冗余。

修复步骤及代码

  1. 正确调用协程函数
    协程函数必须通过await关键字触发执行,不能直接传递协程对象给send()。

  2. 修改定时器函数,实现频道发消息逻辑
    将命令上下文ctx传入函数,通过ctx.channel.send()发送消息,同时优化循环逻辑。

修正后的完整代码

定时器函数部分
import asyncio

time_stamp = {
    "stamp1": {"INTV1": 10},
    "stamp2": {"INTV2": 20},
    "stamp3": {"INTV3": 30}
}

async def TIMER(ctx):
    while True:
        # 按顺序发送三个数字
        await ctx.channel.send(time_stamp["stamp1"]["INTV1"])
        await asyncio.sleep(1)
        await ctx.channel.send(time_stamp["stamp2"]["INTV2"])
        await asyncio.sleep(2)
        await ctx.channel.send(time_stamp["stamp3"]["INTV3"])
        # 可选:设置循环间隔,避免连续重复发送
        await asyncio.sleep(3)
命令调用部分
elif content.startswith("!my_timer"):
    # 异步调用定时器协程,传入上下文以指定发送频道
    await TIMER(ctx)

可选优化:遍历字典动态发送

如果后续需要新增更多数字,可修改循环逻辑,避免硬编码键名:

async def TIMER(ctx):
    while True:
        for stamp in time_stamp.values():
            # 获取每个子字典中的数值
            num = next(iter(stamp.values()))
            await ctx.channel.send(num)
            await asyncio.sleep(1)
        # 循环间隔
        await asyncio.sleep(2)

内容的提问来源于stack exchange,提问作者Nico4O4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 02:42:37