discord.py отправить сообщение в определенный час и дату

#python #discord.py

#python #discord.py

Вопрос:

Я работаю над ботом, который облегчит некоторые задачи, которые мы выполняем в моей команде. С этим я начал создавать некоторые задачи, которые выполняются хорошо, мне нужно создать уведомление, которое будет выполняться с понедельника по пятницу в 16, я видел несколько блогов и безуспешно пытался применить, сегодня это мой код, и функция, которую я хочу вызвать, называется «LEMBRAR ()», с этим я хотел знать, какие опции у меня есть для запуска этого.

 import discord
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions
from BotGooBee.Humor import GooBee

hora = '16:00'
diasSemanas = 'seg-sex'

client = commands.Bot(command_prefix='?')

@client.event
async def on_ready():
    print('bot online')

@client.command()
async def limpar(ctx, amount=100):
    await ctx.channel.purge(limit=amount)

@client.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round(client.latency * 1000)}ms')

@client.command()
async def feliz(ctx):
    GooBee(1).AtualizarHumor()
    await ctx.send('Humor alterado | FELIZ')
    

@client.command()
async def normal(ctx):
    GooBee(2).AtualizarHumor()
    await ctx.send('Humor alterado | NORMAL')

@client.command()
async def irritado(ctx):
    GooBee(3).AtualizarHumor()
    await ctx.send('Humor alterado | IRRITADO')


async def lembrar():
    print('hello')
    channel = client.get_channel(id_channel)
    await channel.send('hello')
    
client.run(token)
  

Ответ №1:

Вы можете использовать модуль datetime, подобный этому, чтобы получить текущее время, затем проверить, правильно ли указано время, а затем запустить функцию.

 import datetime

# Gets the weekday and returns a number: 0 for monday : 6 for sunday
print(datetime.datetime.today().weekday())

# Gets the current time
print(datetime.datetime.now().time())
  

Затем, если это правильный день и время, вы можете запустить функцию.

Комментарии:

1. после .time() вы можете поставить .hour , чтобы получить только час.

Ответ №2:

для тех, у кого есть сомнения, мне удалось создать это предупреждение, следуя совету выше, поэтому я добавил условие в конце bot.loop.create_task (my_def ())

 import discord
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions
from BotGooBee.Humor import GooBee
import asyncio
import json
import random
import datetime

bot = commands.Bot(command_prefix='?')
with open('frases.json', 'r') as json_file:
            dados = json.load(json_file)
@bot.event
async def on_ready():
    print('bot online')

@bot.command()
async def limpar(ctx, amount=100):
    await ctx.channel.purge(limit=amount)

@bot.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round(bot.latency * 1000)}ms')

@bot.command()
async def feliz(ctx):
    GooBee(1).AtualizarHumor()
    await ctx.send('Humor alterado | FELIZ')
    

@bot.command()
async def normal(ctx):
    GooBee(2).AtualizarHumor()
    await ctx.send('Humor alterado | NORMAL')

@bot.command()
async def irritado(ctx):
    GooBee(3).AtualizarHumor()
    await ctx.send('Humor alterado | IRRITADO')
#funcao que faz o alerta da mensagem
async def AlerteHumor():
    await bot.wait_until_ready()
    while not bot.is_closed():
        print('alerta humor')
        hora = int(datetime.datetime.now().time().strftime("%H"))
        minutos = int(datetime.datetime.now().time().strftime("%M"))
        if hora == 16 and minutos <= 59:
            channel = bot.get_channel(channel_id)
            await channel.send(dados[f'{random.randrange(1,5)}'])
        await asyncio.sleep(3600)

bot.loop.create_task(AlerteHumor())
bot.run(token)