Biiarde
Biiarde

Reputation: 11

Discord.py Bot send messages at certain times

I host a discord.py bot on a server for me and some friends, and have been trying to get a certain 'feature', where the bot will send a message every day, twice daily, once in the morning, once in the night, just saying general "good morning" and "good night!" I have spent hours looking through other peoples codes, and similar questions, and this is the best I can find/have gotten (It's taken from another user's 'python alarm', and I tried to hook it up to the bot.

from datetime import datetime
from threading import Timer
x = datetime.today()
y = x.replace(hour=21, minute=45, second=40, microsecond=0)
delta_t = y - x
secs = delta_t.seconds + 1

channel = client.get_channel(806702411808768023)

async def Goodnight():
    await channel.send("Good night! Make sure to go to sleep early, and get enough sleep!")
    print("Night Working")


t = Timer(secs, Goodnight)
t.start()

I keep getting the same error(s), usually about the message not being async or await-'able' (?). I am fairly new to coding/python, sorry if anything is obvious. I really do not know what to do, and I have found some promising solutions, though those make the whole bot the alarm, and force it to 'sleep' while waiting, while I want mine to still function normally (run other commands), if possible? Any help appreciated

Upvotes: 1

Views: 2713

Answers (2)

Rivendare
Rivendare

Reputation: 49

import datetime

@client.event
async def on_ready() -> None:
    print(f'{client.user} is now running!')
    my_task.start()

time = datetime.time(hour=type here, minute=type here)

@tasks.loop(time=time)
async def my_task():
    print("My task is running!")
    async rest of the code here

Upvotes: -2

LoahL
LoahL

Reputation: 2613

This can be done using the tasks extension:

import datetime
import discord
from discord.ext import tasks

client = discord.Client()

goodNightTime = datetime.time(hour=21, minute=45, second=40) #Create the time on which the task should always run

@tasks.loop(time=goodNightTime) #Create the task
async def Goodnight():
    channel = client.get_channel(806702411808768023)
    await channel.send("Good night! Make sure to go to sleep early, and get enough sleep!")
    print("Night Working")

@client.event
async def on_ready():
    if not Goodnight.is_running():
        Goodnight.start() #If the task is not already running, start it.
        print("Good night task started")

client.run(TOKEN)

Note that for that to work you need to have the latest version of either discord.py or a fork which supports version 2.0. If you don't have it yet, you can install it via

pip install -U git+https://github.com/Rapptz/discord.py

Upvotes: 3

Related Questions