#Timeout add duration

1 messages · Page 1 of 1 (latest)

torpid gorge
#

When I timeout someone with Member.timeout, how can I add time to the timeout ?

past spruce
#

Cna you elaborate?

#

Do you mean extend the timeout?

#

Try just setting the timeout until the later time

#

It might work

torpid gorge
past spruce
# torpid gorge ??

Eg if you first did member.timeout(1 day) then just do member.timeout(2 days)

#

Just an example ofc

narrow magnetBOT
#

Here's the timeout example.

torpid gorge
woeful karmaBOT
#

Target not found, try again and make sure to check your spelling.

past spruce
#

Uh

#

One sec

#

.rtfm member.timed

woeful karmaBOT
past spruce
#

That

#

Check if it is true

torpid gorge
#

Can I do this as condition

#

@past spruce ```py
if member is timed_out:
embed = discord.Embed(
title=f"{member} is already timed_out",
description="Would you realy like to expend his sanction ?",
color=discord.Color.red()
)
buttons = [
discord.ui.Button(style=discord.ButtonStyle.green, label="Yes"),
discord.ui.Button(style=discord.ButtonStyle.red, label="No")
]
view = discord.ui.View()
view.add_item(buttons[0])
view.add_item(buttons[1])

await ctx.respond(embed=embed, view=view)

if buttons.labbel == "Yes":
until = datetime.datetime.utcnow() + datetime.timedelta(seconds=duration)
await member.timeout(until=until, reason=reason)
await ctx.respond(f"{duration_str} has been added to {member.mention}'s timer")
else:
await ctx.repond("Operation canceled")```

past spruce
torpid gorge
past spruce
hushed flower
#

If you want to add to the timeout you can get the datetime from Member.communication_disabled_until

past spruce
#

There could have been an alias member.timed_out_until

hushed flower
#

I have no idea why communication_disabled was chossen

torpid gorge
#

@hushed flower I have this error Can You help me please ?

#

AttributeError: 'list' object has no attribute 'labbel'

hushed flower
#

show the code please

#

@torpid gorge

torpid gorge
# hushed flower show the code please
            buttons = [
                discord.ui.Button(style=discord.ButtonStyle.green, label="Yes"),
                discord.ui.Button(style=discord.ButtonStyle.red, label="No")
            ]
            view = discord.ui.View()
            view.add_item(buttons[0])
            view.add_item(buttons[1])

            await ctx.respond(embed=embed, view=view)
            if buttons.labbel == "Yes":
                until = datetime.datetime.utcnow() + datetime.timedelta(seconds=duration)
                await member.timeout(until=until, reason=reason)
                await ctx.respond(f"{duration_str} has been added to {member.mention}'s timer")
            else:
                await ctx.repond("Operation canceled")```
past spruce
#

As you are required to send a response to the interaction

#

You can do the timeout stuff in the button callback

#

Will be easier

#

Check out the examples on GitHub repo and the guide

#

.guide

woeful karmaBOT
torpid gorge
hushed flower
torpid gorge
#

okay

torpid gorge
#

@hushed flower I have no error in the terminal but its showing to me "This application did not respond"

hushed flower
#

Did you run ctx.respond or interaction.response.send_message?

past spruce
torpid gorge
#

Here is all the code ( I don't know were the probleme )

past spruce
#

lets sort this out

#

you need a View subclass

past spruce
# past spruce you need a View subclass

those look smth like

class MyView(discord.ui.View):
  
  @discord.ui.button(...) # stuff like label and style go here
  async def button1(self, button: discord.ui.Button, interaction: discord.Interaction):
    ...

  @discord.ui.button(...)
  async def button2(...): # same as above
    ...
#

you might also need another method def __init__(...) in there depending on the use case

#

in your case, you need to pass the member to timeout

#

so your class will kinda look like

class MyView(discord.ui.View):

  def __init__(self, member: discord.Member):
    super().__init__()
    self.member = member
  
  @discord.ui.button(...)
  async def button1(self, button: discord.ui.Button, interaction: discord.Interaction):
    ...

  @discord.ui.button(...)
  async def button2(...):
    ...
past spruce
past spruce
#

thats it

little cosmos
past spruce
little cosmos
#

it shortcuts member.edit with communication_disabled_until

past spruce
#

didnt knew timeout wasnt a separate endpoint

torpid gorge
#

😫 I am not understanding anything

hushed flower
#

It is strongly recommended to have a grasp of how classes/objects work in python when working with Pycord. You might benefit from taking a bit of time to learn a bit more about them

#

?tag lp

stuck lanternBOT
#
torpid gorge
#

@past spruce @hushed flower @little cosmos

I was able to sort out the issue by, you know, using those decorator thingies in the right way and creating this MyView class to handle button stuff more properly. Also, I figured out that problem with those variables that weren't working, so I passed the time thingy and the reason as some kind of attributes to that MyView thing. So now, when someone clicks the 'Yes' or 'No' buttons, it actually does what it's supposed to do, and the time shows up right in the end message thing.

torpid gorge
# past spruce Wow awesome!!

infact I have just realized that when I press Yes it does send the message but instead of adding time to the sanction it removes the initial time and puts the time to add

example: basic it is 1 hour, I want to add 30 min but it does not display 1h30 min it only takes 30 min because it has removed the initial sanction and put the time added)

past spruce
#

you can add the duration to the existing timeout time if you want

past spruce
torpid gorge
#

@past spruce if I understood correctly you want me to retrieve the current expiry time add the time that I want then delete its delay and put the sum of the two

torpid gorge
#

oh

#

it is obvious that it will be long and painful to make this order but hey I take up the challenge

torpid gorge
past spruce
#

its not that difficult

torpid gorge
#

don't pay attention to the self, it's a Cog

#

No this

#

The two can work

past spruce
torpid gorge
# past spruce This should work

it shows me that

Ignoring exception in view <MyView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Oui' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Program Files\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\alibo\OneDrive\Bureau\PowerBots\PowerBot Moderation\cmd_moderation\mute.py", line 28, in button1
    await self.member.timeout(until=self.member.communication_disabled_until + until, reason=self.reason)
                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'```
past spruce
#

is it until = datetime.now() + duration ?

#

then directly add duration to communication_disabled_until instead of until

torpid gorge
past spruce
torpid gorge
past spruce
# torpid gorge

ok so remove the until = datetime.datetime.utcnow() + ... (3rd line)

#

and do timeout(member.communication_disabled_until + timedelta(self.duration))

past spruce
torpid gorge
past spruce
#

dont directly copy what i said blobpain

#

understand the intent behind it

past spruce
#

to use timedelta(self.duration) instead of until

torpid gorge
#

like that

#

No that

#

but I have an error

past spruce
torpid gorge
#

I add from datetime import timedelta in the code

#

I have this error now :

Ignoring exception in view <MyView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Oui' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Program Files\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\alibo\OneDrive\Bureau\PowerBots\PowerBot Moderation\cmd_moderation\mute.py", line 29, in button1
    await self.member.timeout(self.member.communication_disabled_until + timedelta(self.duration))
  File "C:\Program Files\Python311\Lib\site-packages\discord\member.py", line 854, in timeout
    await self.edit(communication_disabled_until=until, reason=reason)
  File "C:\Program Files\Python311\Lib\site-packages\discord\member.py", line 828, in edit
    data = await http.edit_member(guild_id, self.id, reason=reason, **payload)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\site-packages\discord\http.py", line 371, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body```
torpid gorge
#

@past spruce

past spruce
fast trellis
#

timmeout?

fast trellis
torpid gorge
#

ok

torpid gorge
#

Now I have this

Ignoring exception in view <MuteButtonView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Yes' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Program Files\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\alibo\OneDrive\Bureau\PowerBots\PowerBot Moderation\cmd_moderation\mute.py", line 29, in button_yes
    await self.member.timmeout(until = self.member.communication_disabled_until + datetime.timedelta(self.duration))
          ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'timmeout'```
fast trellis
#

I already mentiond that ^

torpid gorge
#

??

fast trellis
torpid gorge
#

🤦‍♂️

#

same problem

Ignoring exception in view <MuteButtonView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Yes' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Program Files\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\alibo\OneDrive\Bureau\PowerBots\PowerBot Moderation\cmd_moderation\mute.py", line 29, in button_yes
    await self.member.time_out(until = self.member.communication_disabled_until + datetime.timedelta(self.duration))
          ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'time_out'```
#

the problem came from the definition of "self.member"

#

Whit this code

#

I have this error :

Ignoring exception in view <MuteButtonView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Yes' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Program Files\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\alibo\OneDrive\Bureau\PowerBots\PowerBot Moderation\cmd_moderation\mute.py", line 29, in button_yes
    until = self.member.communication_disabled_until + datetime.timedelta(seconds=self.duration)
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'member_descriptor' and 'datetime.timedelta'```
fast trellis
#

Did you add a member object to the class?

torpid gorge
fast trellis
#

I see a no

#

(self, member: discord.Member):

#

self.member = member

torpid gorge
#

the two can work but why not

#

it's ok

torpid gorge
torpid gorge
#

??

torpid gorge
#

@past spruce @hushed flower @fast trellis @little cosmos

I finaly finish the command

#

Here is the code if anyone want to see the code

#
import discord
from discord.ext import commands
from discord.ui import View, Button
import datetime

def format_duration(seconds):
    periods = [("année", 60*60*24*365), ("mois", 60*60*24*30), ("jour", 60*60*24), ("heure", 60*60), ("minute", 60), ("seconde", 1)]
    duration_str = []

    for period_name, period_seconds in periods:
        if seconds >= period_seconds:
            period_value, seconds = divmod(seconds, period_seconds)
            if period_value == 1:
                duration_str.append(f"{period_value} {period_name}")
            else:
                duration_str.append(f"{period_value} {period_name}s")

    return ", ".join(duration_str)

class MuteButtonView(View):
    def __init__(self, member: discord.Member, duration, reason):
        super().__init__()
        self.member = member
        self.duration = duration
        self.reason = reason

    @discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
    async def button_yes(self, button: discord.ui.Button, interaction: discord.Interaction):
        until = self.member.communication_disabled_until + datetime.timedelta(seconds=self.duration)
        await self.member.timeout(until=until, reason=self.reason)
        await interaction.response.send_message(content=f"{format_duration(self.duration)} a été ajouté au temps de {self.member.mention}")
        self.clear_items()

    @discord.ui.button(label="No", style=discord.ButtonStyle.red)
    async def button_no(self, button, interaction):
        await interaction.response.send_message(content="Operation canceled")```
#
class MuteCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="mute", description="Permet d'exclure temporairement un membre")
    async def mute(
        self,
        ctx,
        member: discord.Member,
        days: int = 0,
        hours: int = 0,
        minutes: int = 0,
        seconds: int = 0,
        reason="Aucune raison spécifiée"
    ):
        if member.id == ctx.author.id:
            await ctx.respond("Tu ne peux pas te timeout !")
            return
        if member.guild_permissions.manage_messages:
            await ctx.respond("Tu ne peux pas faire cela, cette personne est un modérateur !")
            return
        duration = days * 86400 + hours * 3600 + minutes * 60 + seconds
        end_time = (datetime.datetime.utcnow() + datetime.timedelta(seconds=duration)).strftime('%Y-%m-%d %H:%M:%S')

        if member.timed_out:
            embed = discord.Embed(
                title=f"{member} is already timed_out",
                description="Would you really like to extend their sanction?",
                color=discord.Color.red()
            )
            view = MuteButtonView(member, duration, reason)
            await ctx.respond(embed=embed, view=view)
        else:
            until = datetime.datetime.utcnow() + datetime.timedelta(seconds=duration)
            await member.timeout(until=until, reason=reason)

            duration_str = format_duration(duration)
            embed = discord.Embed(title="Un membre a été sanctionné !")
            embed.description = f"{member.mention} a été temporairement exclu"
            embed.add_field(name="Temps de la sanction", value=duration_str)
            embed.add_field(name="Nom du juge", value=ctx.author.mention)
            embed.set_footer(text=f"La sanction se terminera {end_time}")
            await ctx.respond(embed=embed)```
narrow magnetBOT
#

This thread was archived by a staff member.

little cosmos
#

uh

#

i dont think it was