discorddiscord.py

how can I check if before.timed_out_until is before present or empty?


this is a stripped down version of my file

the code doesn't work IF: a member got timed out before and that timeout ended naturally. the bot was running for the first time. (somewhat fixed it by getting entries in on_ready() and still sometimes doesn't work)

import discord
import discord.ext
from discord.ext import commands
from discord.ext.commands import Bot
from datetime import datetime

intents = discord.Intents.all()
client = discord.Client(intents=intents)
bot = Bot(command_prefix=".", case_insensitive=True, intents=intents)

@bot.event
async def on_ready():
    print("Bot Hazır" + " " + str(bot.user))

@bot.event
async def on_member_update(before: discord.Member, after: discord.Member):
    memberroleupdate = "AuditLogAction.member_role_update"
    memberupdate = "AuditLogAction.member_update"
    cid = channel_id
    guild = guild_id 
    async for entry in after.guild.audit_logs(limit=1):
        if str(entry.action) == memberupdate:
            #below prints a date if this user has been timed out before
            #and if the mentioned timeout ended naturally
            print(before.timed_out_until)
            print(after.timed_out_until)
            if before.timed_out_until is None:
                #can't reach here when before.timed_out_until prints date
                if after.timed_out_until is not None:
                    async for entry in after.guild.audit_logs(limit=1, action=discord.AuditLogAction.member_update):
                        if entry.target.id == after.id:
                            channel = await bot.fetch_channel(cid)
                            embed = discord.Embed(title="Timeout log",
                                                  description=f"**{after.mention} ({after.id}) adlı kullanıcı {entry.user.mention} ({entry.user.id}) tarafından susturuldu.\nSebep: {entry.reason}**",
                                                  color=discord.Color.blue())
                            embed.set_author(name=f"{after}",
                                             icon_url=f"{after.avatar}")
                            await channel.send(embed=embed)

bot.run("TOKEN")

tried comparing before.timed_out_until with datetime.now() but I wasn't able to compare two dates tried setting before.timed_out_until to None manually but I don't think discord.py works that way

comparing two dates might work but I'm unable to do so

the solution that worked for me:

Changing if after.timed_out_until is not None:


Solution

  • from discord import utils
    
    # ...
    
    if if before.timed_out_until is None or before.timed_out_until < utils.utcnow():
        ... # timed_out_until is in the past