Skip to content

Instantly share code, notes, and snippets.

@Zzz9194
Created September 17, 2020 10:44
Show Gist options
  • Save Zzz9194/7ed6a665df05fee250d6737068fade09 to your computer and use it in GitHub Desktop.
Save Zzz9194/7ed6a665df05fee250d6737068fade09 to your computer and use it in GitHub Desktop.
import discord
def ask(
bot: discord.ext.commands.Bot,
ctx: discord.ext.commands.Context,
question: str,
timeout: float = 30.0,
target_user: discord.Member = None,
target_location: Union[discord.TextChannel, discord.Member] = None,
delete_self: bool = False,
) -> Union[None, str]:
"""
bot: discord.ext.commands.Bot - The bot asking the question
ctx: discord.ext.commands.Context - The context of the invoking command/event
question: str - The question to ask
timeout: float - How long to wait before cancelling automatically
target_user: discord.Member - The user to ask the question to
target_location: Union[discord.TextChannel, discord.Member] - Where to ask the question
delete_self: bool = False - Whether to delete the question-asking message and the answering message or not
"""
if not target_location:
target_location = ctx.channel
if not target_user:
target_user = ctx.author
base_msg = f"Enter `cancel` to cancel the command. The command will automatically cancel in {round(timeout, 0)} seconds."
def _check_valid(msg: discord.Message):
return msg.author == target_user and msg.channel == target_location
async def cancel():
await target_location.send(f"{target_user.mention}, Cancelled the command.")
_q_msg = await target_location.send(
f"{target_user.mention}, {question}\n{base_msg}"
)
try:
_q_wait: discord.Message = await bot.wait_for(
"message", timeout=timeout, check=_check_valid
)
except TimeoutError:
await cancel()
if delete_self:
await _q_msg.delete()
await _q_wait.delete()
return None
else:
if delete_self:
await _q_msg.delete()
await _q_wait.delete()
msg = _q_wait.content
return msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment