diff options
| author | 2019-12-10 22:40:30 +0100 | |
|---|---|---|
| committer | 2019-12-10 22:40:30 +0100 | |
| commit | a80d924eb00ce9485f49c469af0e6acdb1db8dcd (patch) | |
| tree | 749c5127d29474a4be1cf91e79c0c4cb9a98540f /bot/utils | |
| parent | Refactor function signature (diff) | |
| parent | Merge pull request #328 from python-discord/aoc-announcement-mention-fix (diff) | |
Merge branch 'master' into bookmark
Diffstat (limited to 'bot/utils')
| -rw-r--r-- | bot/utils/__init__.py | 23 | 
1 files changed, 23 insertions, 0 deletions
| diff --git a/bot/utils/__init__.py b/bot/utils/__init__.py index 0aa50af6..25fd4b96 100644 --- a/bot/utils/__init__.py +++ b/bot/utils/__init__.py @@ -1,4 +1,5 @@  import asyncio +import contextlib  import re  import string  from typing import List @@ -127,3 +128,25 @@ def replace_many(              return replacement.lower()      return regex.sub(_repl, sentence) + + +async def unlocked_role(role: discord.Role, delay: int = 5) -> None: +    """ +    Create a context in which `role` is unlocked, relocking it automatically after use. + +    A configurable `delay` is added before yielding the context and directly after exiting the +    context to allow the role settings change to properly propagate at Discord's end. This +    prevents things like role mentions from failing because of synchronization issues. + +    Usage: +    >>> async with unlocked_role(role, delay=5): +    ...     await ctx.send(f"Hey {role.mention}, free pings for everyone!") +    """ +    await role.edit(mentionable=True) +    await asyncio.sleep(delay) +    try: +        yield +    finally: +        await asyncio.sleep(delay) +        await role.edit(mentionable=False) | 
