Browse Source
Update background_task example to use ext.tasks
pull/6597/head
Sebastian Law
4 years ago
committed by
GitHub
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with
14 additions and
9 deletions
-
examples/background_task.py
|
|
@ -1,12 +1,16 @@ |
|
|
|
from discord.ext import tasks |
|
|
|
|
|
|
|
import discord |
|
|
|
import asyncio |
|
|
|
|
|
|
|
class MyClient(discord.Client): |
|
|
|
def __init__(self, *args, **kwargs): |
|
|
|
super().__init__(*args, **kwargs) |
|
|
|
|
|
|
|
# create the background task and run it in the background |
|
|
|
self.bg_task = self.loop.create_task(self.my_background_task()) |
|
|
|
# an attribute we can access from our task |
|
|
|
self.counter = 0 |
|
|
|
|
|
|
|
# start the task to run in the background |
|
|
|
self.my_background_task.start() |
|
|
|
|
|
|
|
async def on_ready(self): |
|
|
|
print('Logged in as') |
|
|
@ -14,14 +18,15 @@ class MyClient(discord.Client): |
|
|
|
print(self.user.id) |
|
|
|
print('------') |
|
|
|
|
|
|
|
@my_background_task.before_loop |
|
|
|
async def before_my_task(self): |
|
|
|
await self.wait_until_ready() # wait until the bot logs in |
|
|
|
|
|
|
|
@tasks.loop(seconds=60) # task runs every 60 seconds |
|
|
|
async def my_background_task(self): |
|
|
|
await self.wait_until_ready() |
|
|
|
counter = 0 |
|
|
|
channel = self.get_channel(1234567) # channel ID goes here |
|
|
|
while not self.is_closed(): |
|
|
|
counter += 1 |
|
|
|
await channel.send(counter) |
|
|
|
await asyncio.sleep(60) # task runs every 60 seconds |
|
|
|
self.counter += 1 |
|
|
|
await channel.send(counter) |
|
|
|
|
|
|
|
|
|
|
|
client = MyClient() |
|
|
|