New paste Repaste Download
# Implements SQLite3 database functionality
import sqlite3
import os
from datetime import datetime, timedelta
from contextlib import closing
import discord
### Create and setup databse, if it doesn't exist
if not os.path.exists("database.db"):
    open("database.db", "w").close() # Create database file
    # Create table
    with closing(sqlite3.connect("database.db")) as connection:
        with closing(connection.cursor()) as cursor:
            cursor.execute("CREATE TABLE IF NOT EXISTS ready (user_id INTEGER PRIMARY KEY, time INTEGER)")
### Functions
def insert_time(interaction, hours):
    # Get the timestamp hours from now:
    user_id = interaction.user.id
    time = datetime.now() + timedelta(hours=hours)
    time_int = int(round(time.timestamp()))
    with closing(sqlite3.connect("database.db")) as connection:
        with closing(connection.cursor()) as cursor:
            
            # TODO: This doesn't actually seem to INSERT anything. Why?
            try:
                cursor.execute("INSERT OR REPLACE INTO ready VALUES (?, ?)", (user_id, time_int))
                print(f"User {user_id} ready until {time}")
            except sqlite3.Error as e:
                print(f"SQLite error: {e}")
            
def remove_time(interaction):
    user_id = interaction.user.id
    with closing(sqlite3.connect("database.db")) as connection:
        with closing(connection.cursor()) as cursor:
            try:
                cursor.execute("DELETE FROM ready WHERE user_id = ?", (user_id))
                print(f"User {user_id} no longer ready")
            except sqlite3.Error as e:
                print(f"SQLite error: {e}")
Filename: database.py. Size: 2kb. View raw, , hex, or download this file.
import discord
from discord import app_commands
import database # Import database.py from main folder
# TODO: Use an SQLite database to keep track of role removal times for users
### Helper functions ###
# Return the role to assign to or remove from the user:
async def ready_role(interaction):
    # Get all the ready role IDs from the config and make them into integers:
    ready_role_ids = interaction.client.config["READY_ROLE_IDS"].split(",")
    for i in range(len(ready_role_ids)):
        ready_role_ids[i] = int(ready_role_ids[i])
    # Return the role from the current guild whose ID matches an ID in .env:
    for guild_role in interaction.guild.roles: # All the current guild's roles
        for ready_role_id in ready_role_ids: # All the IDs from .env
            if guild_role.id == ready_role_id: # If one of the guild's roles has a matching ID,
                return guild_role # it is the role we are looking for, so return the role.
# Return True if user already has the role, False otherwise:
async def user_has_role(interaction, role_to_check_for):
    user_roles = interaction.user.roles
    for role in user_roles:
        if role == role_to_check_for:
            return True
    return False
### Commands ###
@app_commands.command (name="r", description="/r hours if you'll be ready for a game for so many hours")
async def ready(interaction: discord.Interaction, hours: int):
    MAX_HOURS = 12
    if MAX_HOURS >= hours > 0:
        role_to_give = await ready_role(interaction)
        await interaction.user.add_roles(role_to_give)
        database.insert_time(interaction, hours)
        await interaction.response.send_message(f"You'll be marked as ready for a game for the next {str(hours)} hours.", ephemeral=True)
    else:
        await interaction.response.send_message(f"🚫 You must enter a value from 1 to {str(MAX_HOURS)} for **hours**.", ephemeral=True)
@app_commands.command (name="n", description="/n if you're no longer ready for a game")
async def notready(interaction: discord.Interaction):
    role_to_remove = await ready_role(interaction)
    if await user_has_role(interaction, role_to_remove):
        await interaction.user.remove_roles(role_to_remove)
        database.remove_time(interaction)
        await interaction.response.send_message("You're no longer marked as ready for a game.", ephemeral=True)
    else:
        await interaction.response.send_message("You're not marked as ready for a game.", ephemeral=True)
### Set up the bot with the above commands ###
async def setup(bot):
    bot.tree.add_command(ready)
    bot.tree.add_command(notready)
Filename: ready.py. Size: 3kb. View raw, , hex, or download this file.

This paste expires on 2025-06-21 20:46:04.986506. Pasted through web.