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, use client.loop.create_task
.
The github of discord.py
has an example of a background task, found here. You should be able to use this as reference. Currently the task posts a message to the given channel every minute, but you can easily modify it to wait for a specific action.
New discord.py
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')
Older discord.py
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')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…