【问题标题】:How to invoke discord function inside the loop如何在循环内调用不和谐函数
【发布时间】:2020-11-27 00:49:40
【问题描述】:

我是 discord py 和 asyncio 的新手。我希望机器人在循环内运行该函数五次。

from discord.ext import commands
Bot = commands.Bot(command_prefix= '!')
a=0
@Bot.event
async def on_ready():
    print('Bot online')
@Bot.command()
async def msg(ctx):
   global a
   a=a+1
   await ctx.author.send(a)

for i in range(5):
   msg()
Bot.run('token')

不幸的是,如果没有在频道中手动输入命令 (!msg),这将不起作用。此外,它不会循环执行。如何调用discord函数作为标准python函数?

【问题讨论】:

    标签: python python-3.x discord python-asyncio discord.py


    【解决方案1】:

    您正在使用没有等待的异步命令

    for _ in range(5):
        await msg()
    

    但是…… 由于您想要使用 msg 函数的方式,我非常怀疑它会起作用 更好的解决方案是

    a = 0
    async def send_message_and_increment(ctx):
        global a
        a += 1
        await ctx.send(a) # send to text_channel the user was in
        await ctx.author.send(a) # send to the user (DM) that invoke the command 
    
    @Bot.command()
    async def msg(ctx):
       global a
    
        for _ in range(5):
            await send_message_and_increment(ctx)
    
    
    

    【讨论】:

    • 还是需要去discord,在channel中写入!msg。有没有办法在没有命令的情况下打印消息?我只需要在频道中每 2 分钟打印一些来自另一个进程的数据。
    • 我发现我可以使用 webhook 代替。无论如何,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 2021-10-05
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2021-08-19
    相关资源
    最近更新 更多