如何修复Discord Bot调用TIMER协程返回对象地址的问题
Discord Bot 定时器函数调用问题修复方案
问题根源
你直接将协程对象(stats_timer = TIMER()生成的实例)传给了send()方法,所以Bot返回了协程的内存地址;同时原TIMER()函数仅打印数字,没有实现发送消息到频道的逻辑,且循环存在冗余。
修复步骤及代码
正确调用协程函数
协程函数必须通过await关键字触发执行,不能直接传递协程对象给send()。修改定时器函数,实现频道发消息逻辑
将命令上下文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
相关产品推荐
相关产品推荐

