Я пытаюсь создать команду тайм-аута для моего бота Discord, но мне нужна помощь с анализом времени.
Команда должна выглядеть так: +timeout @member 2d 3h 40m, но она просто берет 2d, отключает пользователя на 2 дня и в качестве причины указывает «3h 40min», чего делать не следует.
Вот как код пока:
(отсутствуют разрешения/аргументы, а остальные обрабатываются ниже в @timeout.error)
@commands.command(
name="timeout",
aliases=["mute", "t"],
help=""
)
@has_permissions(moderate_members=True)
async def timeout(self, ctx, user: discord.Member, time, *, reason = "No reason provided"):
if user == ctx.author:
await ctx.send("You can't timeout yourself!")
return
if user.top_role >= ctx.guild.me.top_role:
await ctx.send("I can't timeout this user, they have a role that's higher or equal to mine.")
return
if user.top_role >= ctx.author.top_role and ctx.author != ctx.guild.owner:
await ctx.send("You can't timeout this user, they have a role that's higher or equal to yours.")
return
pattern = re.compile(r"(\d+)([smhd])")
matches = list(pattern.finditer(time.lower()))
if not matches:
await ctx.send("Invalid time format, try: 20m, 1h, 3d.")
return
total_duration = datetime.timedelta(0)
for match in matches:
value = int(match.group(1))
unit = match.group(2)
if unit == "s":
total_duration += datetime.timedelta(seconds=value)
elif unit == "m":
total_duration += datetime.timedelta(minutes=value)
elif unit == "h":
total_duration += datetime.timedelta(hours=value)
elif unit == "d":
total_duration += datetime.timedelta(days=value)
timeoutEmbed = discord.Embed(
title = f"Timeout on user {user.name} set successfully.",
description = f"**Reason:** {reason}\n**Moderator:** {ctx.author.mention}")
await ctx.send(embed = timeoutEmbed)
Подробнее здесь: https://stackoverflow.com/questions/797 ... -correctly
Почему моя команда тайм-аута неправильно определяет время? ⇐ Python
Программы на Python
-
Anonymous
1762317376
Anonymous
Я пытаюсь создать команду тайм-аута для моего бота Discord, но мне нужна помощь с анализом времени.
Команда должна выглядеть так: +timeout @member 2d 3h 40m, но она просто берет 2d, отключает пользователя на 2 дня и в качестве причины указывает «3h 40min», чего делать не следует.
Вот как код пока:
(отсутствуют разрешения/аргументы, а остальные обрабатываются ниже в @timeout.error)
@commands.command(
name="timeout",
aliases=["mute", "t"],
help=""
)
@has_permissions(moderate_members=True)
async def timeout(self, ctx, user: discord.Member, time, *, reason = "No reason provided"):
if user == ctx.author:
await ctx.send("You can't timeout yourself!")
return
if user.top_role >= ctx.guild.me.top_role:
await ctx.send("I can't timeout this user, they have a role that's higher or equal to mine.")
return
if user.top_role >= ctx.author.top_role and ctx.author != ctx.guild.owner:
await ctx.send("You can't timeout this user, they have a role that's higher or equal to yours.")
return
pattern = re.compile(r"(\d+)([smhd])")
matches = list(pattern.finditer(time.lower()))
if not matches:
await ctx.send("Invalid time format, try: 20m, 1h, 3d.")
return
total_duration = datetime.timedelta(0)
for match in matches:
value = int(match.group(1))
unit = match.group(2)
if unit == "s":
total_duration += datetime.timedelta(seconds=value)
elif unit == "m":
total_duration += datetime.timedelta(minutes=value)
elif unit == "h":
total_duration += datetime.timedelta(hours=value)
elif unit == "d":
total_duration += datetime.timedelta(days=value)
timeoutEmbed = discord.Embed(
title = f"Timeout on user {user.name} set successfully.",
description = f"**Reason:** {reason}\n**Moderator:** {ctx.author.mention}")
await ctx.send(embed = timeoutEmbed)
Подробнее здесь: [url]https://stackoverflow.com/questions/79761266/why-doesnt-my-timeout-command-take-time-correctly[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия