首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将上下文传递给后台任务discord.py

将上下文传递给后台任务discord.py
EN

Stack Overflow用户
提问于 2018-05-18 09:09:15
回答 2查看 4.1K关注 0票数 2

discord上的一个服务器所有者让我为他在我的机器人中添加一个自定义货币系统(机器人只在这台服务器上)。为了鼓励活动,我们没有使用dailies系统,相反,我的想法是每7分钟弹出一条带有图片的消息,用户必须在图片上添加“反应”。为了简单和控制输入,我想要在我的图像中添加一个反应,这样用户只需单击该反应,它就会添加数量。

在排除了所有这些上下文的情况下,这里将问题作为后台任务。我不知道如何将上下文传递给反应!

async def my_background_task():
    await bot.wait_until_ready()
    counter = 0
    channel = discord.Object(id='446782521070321664')
    while not bot.is_closed:
        counter += 1
        with open('vbuck.png', 'rb') as f:
            await bot.send_file(channel, f) #sends a png of a vbuck
            await bot.add_reaction(discord.message,'<:vbuck:441740047897591809>') #This is the Reaction part 
    await asyncio.sleep(420) # task runs every 7 min seconds
bot.loop.create_task(my_background_task())

如果你能给我建议,这将是伟大的,如果你觉得额外慷慨的代码+解释将不胜感激,我正在学习这个项目的python。

EN

回答 2

Stack Overflow用户

发布于 2019-04-01 12:35:19

您需要保存send_file返回的Message对象(发送的消息)。然后,您可以在Client.wait_for_reaction中使用该Message对象来等待反应。

async def task():
    await bot.wait_until_ready()
    channel = discord.Object(id='446782521070321664')
    vbuck = discord.utils.get(bot.get_all_emojis(), name='vbuck')
    check = lambda reaction, user: user != bot.user
    while not bot.is_closed:
        msg = await bot.send_file(channel, 'vbuck.png') #sends a png of a vbuck
        await bot.add_reaction(msg, vbuck) 
        for _ in range(7*60):
            res = await bot.wait_for_reaction(message=msg, emoji=vbuck, check=check, timeout=1)
            if res:
                # res.user reacted to the message
票数 1
EN

Stack Overflow用户

发布于 2019-04-01 07:31:05

如果我没理解错的话,你想要真正等待用户对你发布的文件的反应,然后奖励他们的反应。我假设您使用的是discord.py 1.0或更高版本。

据我所知,后台任务本身不能传递任何上下文-因为它不像在特定上下文中的注释一样被调用。但是,接口(https://discordpy.readthedocs.io/en/rewrite/api.html#discord.on_reaction_add)声明有一个监听消息上的反应,这意味着您可以简单地使用

@bot.event
async def on_reaction_add(reaction, user):
    #here do some checks on reaction.message and to check that it is actually
    #the correct message being reacted too and avoid multiple reactions of one user.

API还会告诉您可以对消息执行哪种类型的检查。当让机器人发布消息时,您可以给它一个特定的签名(像time.time()这样的时间戳似乎足够好),然后访问reaction.message.content并将其与当前时间进行比较。为此,我会将您的后台任务修改为如下所示:

async def my_background_task():
    await bot.wait_until_ready()
    counter = 0
    channel = bot.get_channel(id='446782521070321664')

    while not bot.is_closed:
        counter += 1
        mess = "maybe a timestamp"
        e = discord.Embed()
        e.set_image(url = "some cool image maybe randomly chosen, please no vbucks")
        await channel.send(mess, embed = e) #sends a message with embed picture
        await asyncio.sleep(420) # task runs every 7 min

然后,消息内容将简单地为message

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50402437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档