我可以在异步循环任务旁边运行消息侦听器吗?

问题描述

我正在使用discord.py创建一个机器人,该机器人会定期在Anilist上查找用户更新。此任务使用discord.Client.loop.create_task(task)运行,并且按预期方式工作。但是,当我尝试在此任务旁边使用消息侦听器时,该漫游器不会响应。我之前已经测试了此代码段,并且可以正常工作,但是与该任务一起无法正常工作。

我查看了discord.py文档和asyncio.AbstractEventLoop上的create_task文档,但是没有有关与AbstractEventLoop同时运行消息侦听器的信息。

client = discord.Client()

#message listener
@client.event
async def on_message(message):
    if message == ".help":
        message.channel.send("test")

#background task
@client.event
@client.event
async def my_background_task():
    await client.wait_until_ready()
    channel = client.get_channel(458644594905710595)
    while not client.is_closed():
        curr_time = int(time.time()-2)
        variables_pat = {
            'userId': 121769,'createdAt_greater': curr_time
        }

        variables_hani = {
            'userId': 320308,'createdAt_greater': curr_time

        }

        variables_phil = {
            'userId': 163795,'createdAt_greater': curr_time
        }

        variables_alan = {
            'userId': 121839,'createdAt_greater': curr_time
        }

        variables_ben = {
            'userId': 122953,'createdAt_greater': curr_time
        }

        variables_zen = {
            'userId': 382311,'createdAt_greater': curr_time
        }

        variables_me = {
            'userId': 323865,'createdAt_greater': curr_time
        }

        variables_min = {
            'userId': 169966,'createdAt_greater': curr_time
        }
        arr_vars = [variables_alan,variables_ben,variables_hani,variables_pat,variables_phil,variables_zen,variables_me,variables_min]
        for variables in arr_vars:
            response = requests.post(url,json={'query': query,'variables': variables})
            my_json = json.loads(response.content)
            if my_json["data"] is not None and my_json["data"]["Activity"] is not None:
                activity = my_json["data"]["Activity"]
                print(activity)
                if activity["progress"] is not None:
                    result_string = activity["user"]["name"] + " " + activity["status"] + " " + activity["progress"] + " of " + activity["media"]["title"]["romaji"]
                    result_embed = discord.Embed(
                        title="New Anilist Post",color=discord.Color(0x039AFF),description=result_string
                    )
                    await channel.send(embed=result_embed)
                else:
                    result_string = activity["user"]["name"] + " " + activity["status"] + " " + activity["media"]["title"]["romaji"]
                    result_embed = discord.Embed(
                        title="New Anilist Post",description=result_string
                    )
                    await channel.send(embed=result_embed)

client.loop.create_task(my_background_task())
client.run(os.getenv("disCORD_TOKEN"))

解决方法

您可以执行所需的操作,但是应该使用命令框架。这是一个例子

import discord
from discord.ext import commands,tasks

bot = commands.Bot(command_prefix='-')

bot.remove_command('help') # Remove the built-in help command since we have our own

@bot.event
async def on_ready():
    # Once the bot has connected and is ready to go
    bot.my_current_task = my_task.start()

@tasks.loop(minutes=1) # Run every minute,takes hours,minutes,etc
async def my_task():
    # Put the code to be executed every loop here
    print("The loop hath run")

@my_task.before_loop # Before we start the loop make sure the bot is ready to go
async def before_my_task():
    await bot.wait_until_ready()

# Now the commands framework is nice,no longer do you need to handle commands within on_message
@bot.command()
async def help(ctx):
    await ctx.send("Hello and welcome to my help command")

bot.run("TOKEN HERE")

在这里使用您的代码,然后简单地转换为使用aiohttp 希望对您有帮助,任何问题都可以随时提出!