событие on_message () реагирует только каждые x минут, сохраняя время

#python #json #discord.py

#python #json #discord.py

Вопрос:

Я пытаюсь заставить бота сказать пользователям ложиться спать, если они отправят сообщение в определенный период времени, но бот реагирует только каждые x минут. Это делается путем проверки, превышает ли разница во времени между текущим и последним сообщением x . В настоящее время на выходе просто ничего — даже ошибок.

Мне удалось получить эквивалент желаемого результата в «обычном» python с:

 import datetime
import json
now = datetime.datetime.now()
nowHourMin = float( now.hour )   ( float( now.minute )/60 )   

def get_time():
    filename = "messageRecord.json"
    try:                                 #If file exists, get time of last message
        with open(filename, "r") as f:
            lastMessage = json.load(f)
    except FileNotFoundError:            #If file doesn't exists, create it and store current time
        lastMessage = nowHourMin
        with open(filename, "w") as f:
            json.dump(lastMessage, f)
    return lastMessage

def update_time():                       #Store current time
    filename = "messageRecord.json"
    with open(filename, "w") as f:
        json.dump(nowHourMin, f)           
    
def message_responder():
    lastMessage = get_time()
    dt = nowHourMin - lastMessage
    if (nowHourMin < 23 ) and (dt >0.01):
        print("Please go to bed, it is getting late")
    update_time()

message_responder()
  

Но когда я пытаюсь адаптировать код к библиотеке discord, я не получаю никакого результата. Файл json не создается, и когда я создаю его сам, в файл ничего не записывается. Он также не выдает никаких ошибок, просто ничего. Другие команды и события работают нормально.
Вот discord.py версия:

 import discord
import json
import datetime
from discord.ext import commands, tasks

now = datetime.datetime.now()
nowHourMin = float( now.hour )   ( float( now.minute )/60 )

async def get_time():
    filename = "messageRecord.json"
    try:                                #If file exists, get time of last message
        with open(filename, "r") as f:
            lastMessage = json.load(f)
    except FileNotFoundError:           #If file doesn't exists, create it and store current time
        lastMessage = nowHourMin
        with open(filename, "w") as f:
            json.dump(lastMessage, f)
    return lastMessage

async def update_time():
    filename = "messageRecord.json"
    with open(filename, "w") as f:
        json.dump(nowHourMin, f)                       

def message_responder(message):
    lastMessage = get_time()                            #Get time of last message from "messageRecord.json"
    dt = nowHourMin - lastMessage                       #Time difference
    if (message.author != client.user) and (nowHourMin < 23 ) and (dt >0.01):   #Values will be adjusted once bot works
        await message.channel.send("Please go to bed, it is getting late")
    else:
        await message.channel.send("Dummy text")        #Will be removed once code works, just to confirm bot is working.
    await update_time()                                 #Updates lastMessage to now

@client.event
async def on_message(message):
    await message_responder(message)
    await client.process_commands(message)              #Prevents on_message()from overwriting commands
  

Ответ №1:

Вам нужно ожидать get_time() , поскольку это асинхронная функция. Вам также необходимо сделать message_responder() асинхронным:

 async def message_responder(message): #<- here
    lastMessage = await get_time() #<- and here
    dt = nowHourMin - lastMessage
    if (message.author != client.user) and (nowHourMin < 23 ) and (dt >0.01):
        await message.channel.send("Please go to bed, it is getting late")
    else:
        await message.channel.send("Dummy text")
    await update_time()