The reason your code is not working is because client.run is blocking, meaning that nothing after it will execute. This means your loop will never be reached.
To get around this, you can use the tasks extension, which was introduced in version 1.1.0 of discord.py. The GitHub has an example of a background task. The below code will post the current iteration of the loop to a channel every minute, but you can easily modify it to wait for a specific action.
import discord
from discord.ext import tasks
client = discord.Client(intents=discord.Intents.all())
@tasks.loop(seconds=60)
async def my_background_task():
await client.wait_until_ready()
channel = client.get_channel(123456789) # replace with channel_id
await channel.send(my_background_task.current_loop)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
my_background_task.start()
client.run('token')
Older versions of discord.py
For older versions of discord.py, use client.loop.create_task. An example of a background task can also be found here.
discord.py < 1.1.0 versions
import discord
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = client.get_channel(id=123456789) # replace with channel_id
while not client.is_closed():
counter += 1
await channel.send(counter)
await asyncio.sleep(60) # task runs every 60 seconds
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run('token')
discord.py < 1.0 versions
import discord
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='channel_id_here')
while not client.is_closed:
counter += 1
await client.send_message(channel, counter)
await asyncio.sleep(60) # task runs every 60 seconds
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.loop.create_task(my_background_task())
client.run('token')