Answer the question
In order to leave comments, you need to log in
How to make tasks.loop auto unban after timeout using SQLITE3 Discord.py?
Hello, I need help for two days now I can’t make a function so that after the time expires, the user is unbanned.
The data is stored in the SQLite3 database, the date of the ban is in the format 21-11-2021
Inserted the ban cmd code, libraries, sqlite3, tasks unbanned.
Here is the code:
import discord
from discord import *
from discord.ext import commands, tasks
from discord.ext.commands import Bot
from discord_components import DiscordComponents, Button, ButtonStyle
import sqlite3
import threading
from datetime import datetime
from datetime import date
from datetime import timedelta
import time
# DataBase
db = sqlite3.connect('baza.db', check_same_thread=False)
sql = db.cursor()
sql.execute(f"SELECT * FROM settings")
if sql.fetchone() is None:
sql.execute(f"INSERT INTO settings VALUES ('.')")
db.commit()
else:
pass
# Configs
for settings in sql.execute(f"SELECT * FROM settings"):
PREFIX = settings[0]
lock = threading.Lock()
intents = discord.Intents().all()
client = commands.Bot(command_prefix=PREFIX,intents=intents)
sql.execute(f"SELECT * FROM bans")
getallbannedid = []
for getallbid in sql.execute(f"SELECT * FROM bans"):
getallbannedid += [getallbid[0]]
print(getallbannedid)
# Евенты
@client.event
async def on_ready():
DiscordComponents(client)
print("Бот запущен!")
ban_loop.start()
await client.change_presence(status = discord.Status.online, activity = discord.Game('by semmy#0068'))
# команды
@client.command(pass_context=True)
async def ban(ctx, member: discord.Member, daysss, reason, daysdelmsg):
for info in sql.execute(f"SELECT * FROM users WHERE id = {ctx.author.id}"):
accessquery = 3
if info[1] >= accessquery:
currenttime = datetime.now()
getuserid = member.id
emb = discord.Embed(description = f'**Блокировка аккаунта**', colour = discord.Color.red())
emb.add_field(name = '**Пользователь**', value = f"<@!{member.id}>")
emb.add_field(name = '**Причина**', value = f"{reason}")
emb.add_field(name = '**Длительность**', value = f"{daysss} дней")
emb.add_field(name = '**Дата выдачи**', value = f"{currenttime}")
emb.add_field(name = '**Модератор**', value = f"<@!{ctx.author.id}>")
emb.set_footer(text="© FakePixel Administraion")
emb.set_author(name=client.user.name, icon_url=client.user.avatar_url)
global getuserbannedid
getuserbannedid = member.id
sql.execute(f"SELECT banned FROM bans WHERE banned = {getuserid}")
if sql.fetchone() is None:
getnowdata = datetime.now().date()
dayss = getnowdata + timedelta(days=int(daysss))
sql.execute(f"INSERT INTO bans VALUES ({member.id}, {ctx.author.id}, '{dayss}', '{reason}', '{currenttime}')")
db.commit()
else:
sql.execute(f"INSERT INTO bans VALUES ({member.id}, {ctx.author.id}, '{dayss}', '{reason}', '{currenttime}')")
db.commit()
await member.ban(delete_message_days=daysdelmsg)
await ctx.send(embed=emb)
@tasks.loop(seconds=2.0)
async def ban_loop():
await client.wait_until_ready()
for bans in sql.execute(f"SELECT * FROM bans"):
getdatanow = datetime.now().date()
await client.wait_until_ready()
if str(getdatanow) > bans[2]:
guild = client.get_guild(806633419865718784)
await guild.unban(getallbannedid[4])
print(getallbannedid[4])
sql.execute(f"DELETE FROM bans WHERE banned = {bans[0]}")
db.commit()
print('Пользователь разбанен по истечению длительности наказания')
Answer the question
In order to leave comments, you need to log in
why call await client.wait_until_ready() in the for bans loop in the ban_loop() function? It will slow down the cycle for who knows how much. Same with calling ban_loop() at the beginning - you have an on_ready() handler, you run ban_loop() there, this ensures that the loop starts when the bot is ready to run.
Further, why select all bans and scroll through them when you can set SELECT to select only expired bans?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question