Home > Net >  How to send a message using discord.py into a channel without input but on true condition
How to send a message using discord.py into a channel without input but on true condition

Time:01-14

here is my code i'm trying to integrate with a script that runs 24/7

import discord

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_ready():
    channel = client.get_channel(3534536365654654)
    await channel.send("Bot is ready")


@client.event
async def background_task():
    channel = client.get_channel(3534536365654654)
    embed = discord.Embed(title="Testing")
    embed.add_field(name="Req Amount", value="100")
    embed.add_field(name="Return Amount", value="120")
    await channel.send(embed=embed)

client.run(token)

basically every time my condition sets to true in the main code i want to run background_task() in the main file but right now while running just this code only the on_ready() function is sending an output.

My bot is not supposed to take any inputs or commands just send the message each time the condition is true in code.

I've also tested all previous solutions and they have been rendered useless after the async update to discord.py

Any help would be appreciated

CodePudding user response:

Use tasks and just have it run every few minutes (or hours/whatever) and check that the condition you want is True - if it is then send the message you want to send.

The @client.event syntax is usually reserved for actual client events - so background_task is never going to be executed.

CodePudding user response:

Have a look in to discord.ext.tasks

Here's a simple example which executes every 5 seconds. With every loop you can check on a value and perform the actions accordingly.

from discord.ext import tasks, commands

@tasks.loop(seconds=5.0)
async def bg_task(self):
    if value:
        // Do something on True
    else:
        // Do something on False
  • Related