Search code examples
pythondiscorddiscord.py

sending a message through a discord bot when a condition is met


I would like to send automated discord message through the bot when a does not equal b. I have other commands working but they all require user input through discord

from discord.ext import commands
import requests
import time
import threading

client = commands.Bot(command_prefix = '!')
TOKEN = ('my bot token')


def rep():
  threading.Timer(10.0, rep).start()
rep.a = ("aaa")
rep.b = ("bbb")
if rep.a == rep.b :
    print("a does in fact equal b")
    #other stuff

else:
    print("a does not equal b")
    #send a message through the discord bot
    #other stuff
rep()

client.run(TOKEN)

Solution

  • discord.py actually has loops built in

    I think this should help:

    from discord.ext import tasks
    
    @client.event
    async def on_ready():
        
        your_loop_name.start()
    
    a = "aaa"
    b = "bbb"
    
    
    @tasks.loop(seconds=10)
    async def your_loop_name():
        global a, b
        print(a)
        print(b)
        if a != b:
            # You can put everything here, this is just an example
            user = client.get_user(PUT_YOUR_USER_ID_HERE)
            await user.send('a is not equal to b')
        else:
            pass
    
    # ----------------
    
    @client.command()
    async def change(ctx, a_b="-", *, value=None):
        global a, b
        if a_b == "a":
            if not value:
                return
            a = value
        elif a_b == "b":
            if not value:
                return
            b = value
        else:
            await ctx.send(f"Please enter a or b")
    

    The loop executes every 10 seconds, and checks if a is not equal b ( != )

    If you execute the command "change b aaa" The Bot will stop sending you that it is not equal and will print "aaa" 2x!