Skip to content

Instantly share code, notes, and snippets.

@sgtlaggy
Last active July 9, 2021 20:04
Show Gist options
  • Save sgtlaggy/af5752ce5c02f2da2cffef3ffd2cee00 to your computer and use it in GitHub Desktop.
Save sgtlaggy/af5752ce5c02f2da2cffef3ffd2cee00 to your computer and use it in GitHub Desktop.
?tag list 103714384802480128
import datetime
from discord.ext import tasks
import discord
@tasks.loop(hours=24)
async def daily_task():
do_task_stuff()
@daily_task.before_loop
async def wait_until_7am():
# this will use the machine's timezone
# to use a specific timezone use `.now(timezone)` without `.astimezone()`
# timezones can be acquired using any of
# `datetime.timezone.utc`
# `datetime.timezone(offset_timedelta)`
# `pytz.timezone(name)` (third-party package)
now = datetime.datetime.now().astimezone()
next_run = now.replace(hour=7, minute=0, second=0)
if next_run < now:
next_run += datetime.timedelta(days=1)
await discord.utils.sleep_until(next_run)
from discord.ext import tasks
@tasks.loop()
async def yourtask():
# if you don't care about keeping records of old tasks, remove this WHERE and change the UPDATE to DELETE
next_task = await db_conn.fetchrow('SELECT * FROM tasks WHERE NOT completed ORDER BY end_time LIMIT 1')
# if no remaining tasks, stop the loop
if next_task is None:
yourtask.stop()
# sleep until the task should be done
await discord.utils.sleep_until(next_task['end_time'])
# do your task stuff here with `next_task`
# delete the task or mark it as completed
await db_conn.execute('UPDATE tasks SET completed = true WHERE row_id = $1', next_task['row_id'])
# if the bot needs to be logged in before task runs
@yourtask.before_loop
async def before_yourtask():
await bot.wait_until_ready()
yourtask.start()
# in a command that adds new task in db
if yourtask.is_running():
yourtask.restart()
else:
yourtask.start()
async def run_once_when_ready():
await bot.wait_until_ready()
print('Bot is ready.')
bot.loop.create_task(run_once_when_ready())
bot.run(TOKEN)
message = await ctx.send('React with \N{PARTY POPPER} within 60 seconds.')
users = {} # set for only unique users
# get all users who react to that message with 🎉
def check(r, u):
if r.message == message and str(r.emoji) == '\N{PARTY POPPER}':
users.add(u)
return len(users) == 10 # OPTIONAL, only allow a specific number of reactions
with contextlib.suppress(asyncio.TimeoutError): # TimeoutError is expected, it can be ignored
await bot.wait_for('reaction_add', check=check, timeout=60)
# `users` is a set of users who reacted within the time limit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment