Files
main.py
requirements.txt
Code
2 422
main.py
import csv
import io
import logging
import os
import sqlite3
import time
from datetime import datetime, timezone
from typing import Optional
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("ems_mesai")
DATABASE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mesai.db")
logger.info("Mesai veritabanı dosyası: %s", DATABASE_PATH)
DATABASE = sqlite3.connect(DATABASE_PATH)
DATABASE.execute("PRAGMA journal_mode=WAL")
DATABASE.execute(
"""CREATE TABLE IF NOT EXISTS attendance (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
total_seconds INTEGER NOT NULL DEFAULT 0,
started_at INTEGER,
PRIMARY KEY (guild_id, user_id)
)"""
)
DATABASE.execute(
"""CREATE TABLE IF NOT EXISTS adjustments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
target_id INTEGER NOT NULL,
actor_id INTEGER NOT NULL,
seconds INTEGER NOT NULL,
reason TEXT NOT NULL,
created_at INTEGER NOT NULL
)"""
)
DATABASE.execute(
"""CREATE TABLE IF NOT EXISTS attendance_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
action TEXT NOT NULL,
duration_seconds INTEGER,
created_at INTEGER NOT NULL
)"""
)
DATABASE.commit()
def format_duration(seconds: int) -> str:
seconds = max(0, int(seconds))
hours, remainder = divmod(seconds, 3600)
minutes, remaining_seconds = divmod(remainder, 60)
result = f"{hours} saat {minutes} dakika"
if hours == 0 and minutes == 0:
result += f" {remaining_seconds} saniye"
return result
def get_attendance(guild_id: int, user_id: int):
return DATABASE.execute(
"SELECT total_seconds, started_at FROM attendance WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
).fetchone()
def current_total(row, now: Optional[int] = None) -> int:
if row is None:
return 0
total_seconds, started_at = row
if started_at is not None:
total_seconds += max(0, (int(time.time()) if now is None else now) - started_at)
return total_seconds
def is_staff(interaction: discord.Interaction) -> bool:
if interaction.guild is None or not isinstance(interaction.user, discord.Member):
return False
permissions = interaction.user.guild_permissions
return permissions.administrator or permissions.manage_guild
class AttendanceView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(
label="Mesaiye Başla",
emoji="🟢",
style=discord.ButtonStyle.success,
custom_id="ems:clock_in:v1",
)
async def clock_in(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.guild is None:
await interaction.response.send_message("Bu buton yalnızca sunucuda kullanılabilir.", ephemeral=True)
return
now = int(time.time())
row = get_attendance(interaction.guild.id, interaction.user.id)
if row is not None and row[1] is not None:
await interaction.response.send_message("Zaten mesaidesiniz. 🚑", ephemeral=True)
return
with DATABASE:
DATABASE.execute(
"""INSERT INTO attendance (guild_id, user_id, total_seconds, started_at)
VALUES (?, ?, 0, ?)
ON CONFLICT(guild_id, user_id) DO UPDATE SET started_at = excluded.started_at""",
(interaction.guild.id, interaction.user.id, now),
)
DATABASE.execute(
"""INSERT INTO attendance_logs (guild_id, user_id, action, created_at)
VALUES (?, ?, 'GİRİŞ', ?)""",
(interaction.guild.id, interaction.user.id, now),
)
await interaction.response.send_message(
f"🟢 {interaction.user.mention}, mesaiye giriş yaptınız. Başlangıç: <t:{now}:t>",
ephemeral=True,
)
@discord.ui.button(
label="Mesaiden Çık",
emoji="🔴",
style=discord.ButtonStyle.danger,
custom_id="ems:clock_out:v1",
)
async def clock_out(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.guild is None:
await interaction.response.send_message("Bu buton yalnızca sunucuda kullanılabilir.", ephemeral=True)
return
now = int(time.time())
row = get_attendance(interaction.guild.id, interaction.user.id)
if row is None or row[1] is None:
await interaction.response.send_message("Şu anda mesaide görünmüyorsunuz.", ephemeral=True)
return
session_seconds = max(0, now - row[1])
total_seconds = row[0] + session_seconds
with DATABASE:
DATABASE.execute(
"UPDATE attendance SET total_seconds = ?, started_at = NULL WHERE guild_id = ? AND user_id = ?",
(total_seconds, interaction.guild.id, interaction.user.id),
)
DATABASE.execute(
"""INSERT INTO attendance_logs (guild_id, user_id, action, duration_seconds, created_at)
VALUES (?, ?, 'ÇIKIŞ', ?, ?)""",
(interaction.guild.id, interaction.user.id, session_seconds, now),
)
await interaction.response.send_message(
f"🔴 {interaction.user.mention}, mesaiden çıkış yaptınız.\n"
f"Bu mesai: **{format_duration(session_seconds)}**\n"
f"Toplam mesai: **{format_duration(total_seconds)}**",
ephemeral=True,
)
class EMSBot(commands.Bot):
async def setup_hook(self):
self.add_view(AttendanceView())
await self.tree.sync()
logger.info("Slash komutları Discord ile eşitlendi.")
bot = EMSBot(command_prefix="!", intents=discord.Intents.default())
synced_guilds: set[int] = set()
@bot.tree.command(name="mesai-panel", description="EMS mesai giriş/çıkış panelini oluşturur.")
@app_commands.check(is_staff)
async def mesai_panel(interaction: discord.Interaction):
embed = discord.Embed(
title="🚑 EMS | Personel Mesai Sistemi",
description=(
"Mesai durumunuzu aşağıdaki butonlarla kaydedin.\n"
"Mesaiye başladığınızda süre işlemeye başlar; çıkış yaptığınızda geçen süre toplamınıza eklenir."
),
color=discord.Color.from_rgb(39, 174, 96),
)
embed.add_field(name="🟢 Giriş", value="Vardiyanıza başlamak için **Mesaiye Başla** butonuna basın.", inline=False)
embed.add_field(name="🔴 Çıkış", value="Vardiyanızı tamamlamak için **Mesaiden Çık** butonuna basın.", inline=False)
embed.set_footer(text="EMS Personel Yönetimi • Mesai kayıtları kalıcı olarak saklanır")
await interaction.response.send_message(embed=embed, view=AttendanceView())
@bot.tree.command(name="mesai-durum", description="Bir personelin toplam ve aktif mesai süresini gösterir.")
async def mesai_durum(interaction: discord.Interaction, uye: Optional[discord.Member] = None):
if interaction.guild is None:
await interaction.response.send_message("Bu komut yalnızca sunucuda kullanılabilir.", ephemeral=True)
return
