如何在discord.py事件循环中添加函数? [英] How to add a function to discord.py event loop?

查看:46
本文介绍了如何在discord.py事件循环中添加函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Python与 discord.py 一起使用.文档 此处

I am using Python with discord.py. Documentation here

我有一个在Discord服务器上运行的机器人,该机器人将服务器与subreddit链接在一起.用户具有各种命令,这些命令可以执行诸如获取最高提交,获取最新提交等操作.

I've got a bot that is running on a Discord server that links the server with a subreddit. Users have various commands that do things like getting the top submissions, getting the latest submissions, and so on.

我想向机器人添加一些功能,其中之一是关键字通知程序.漫游器应在subreddit中搜索标题中的关键字,然后通知用户它们是否在该关键字的列表中.我知道如何做到这一点,我已经做了很多次,但是我不知道如何使用Discord机器人来做到这一点.我没有使用asynchio或任何类型的异步编程的经验.

I want to add some features to the bot, with one of them being a keyword notifier. The bot should search the subreddit for keywords in the title, and then notify users if they are on the list for that keyword. I know how to do this, I've done it plenty of times, but I don't know how to do it with a Discord bot. I have no experience with asynchio or any kind of asynchronous programming.

我尝试做的方式行得通,但它非常简陋,绝对不好.在 on message()函数的顶部,我只添加了对 search_submissions()函数的调用,以便每当有人放置在服务器上发送新消息时,该机器人将扫描Reddit提交的内容.服务器很忙,可以正常工作,但是我真的想以适当"的方式来做.

The way I've tried to do it works, but it is very janky and definitely not good. At the top of the on message() function, I just add a call to the search_submissions() function, so that whenever someone puts sends a new message on the server, the bot will scan the Reddit submissions. The server is busy enough that this would work relatively okay, but I really want to do it the "proper" way.

我不知道如何调用 search_submissions()函数而不将其放在 on_message()中.

I don't know how to call the search_submissions() function without putting it inside of on_message().

编辑其他代码:

import discord

TOKEN = "redacted"
client = discord.Client()

@client.event
async def reddit_search():
    print("Searching")

@client.event
async def on_message(message):
    if message.content.startswith("reddit!hot"):
        # Get hot
    # Do other things.

@client.event
async def on_ready():
    print("Connected to Discord as {}.".format(client.user.name))

client.run(TOKEN)

推荐答案

您可以使用 Client.loop.create_task(search_submissions())向bot事件循环添加一个函数,如下所示:

You can add a function to the bot event loop with Client.loop.create_task(search_submissions()) like this:

async def search_submissions():
    pass

client = discord.Client()

client.loop.create_task(search_submissions())
client.run(TOKEN)


更新:

如果您希望函数继续运行,可以将其置于while循环中,并在其间进行一些睡眠:

If you want your function to continue working you can put it in a while loop with some sleeping in between:

async def search_submissions():
    while(true):
        # do your stuff
        await asyncio.sleep(1)

这篇关于如何在discord.py事件循环中添加函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆