Files
bot.py
requirements.txt
Code
2 1,406
bot.py
import logging
import io
import os
import sqlite3
from contextlib import contextmanager
from pathlib import Path
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
DATABASE_PATH = Path(__file__).with_name("middleman.sqlite3")
FINAL_STATUSES = {"completed", "resolved_completed", "resolved_cancelled"}
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("middleman_bot")
@contextmanager
def database():
connection = sqlite3.connect(DATABASE_PATH)
connection.row_factory = sqlite3.Row
try:
yield connection
connection.commit()
except Exception:
connection.rollback()
raise
finally:
connection.close()
def initialize_database():
with database() as connection:
connection.execute(
"""CREATE TABLE IF NOT EXISTS deals (
channel_id INTEGER PRIMARY KEY,
guild_id INTEGER NOT NULL,
buyer_id INTEGER NOT NULL,
seller_id INTEGER NOT NULL,
details TEXT NOT NULL,
status TEXT NOT NULL,
buyer_accepted INTEGER NOT NULL DEFAULT 0,
seller_accepted INTEGER NOT NULL DEFAULT 0,
message_id INTEGER,
resolution_note TEXT NOT NULL DEFAULT ''
)"""
)
connection.execute(
"""CREATE TABLE IF NOT EXISTS guild_settings (
guild_id INTEGER PRIMARY KEY,
staff_role_id INTEGER NOT NULL
)"""
)
connection.execute(
"""CREATE TABLE IF NOT EXISTS tickets (
channel_id INTEGER PRIMARY KEY,
guild_id INTEGER NOT NULL,
owner_id INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'open',
claimed_by INTEGER
)"""
)
connection.execute(
"""CREATE TABLE IF NOT EXISTS bot_metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)"""
)
def create_deal(guild_id, channel_id, buyer_id, seller_id, details):
with database() as connection:
connection.execute(
"INSERT INTO deals (guild_id, channel_id, buyer_id, seller_id, details, status) "
"VALUES (?, ?, ?, ?, ?, 'awaiting_agreement')",
(guild_id, channel_id, buyer_id, seller_id, details),
)
def get_deal(channel_id):
with database() as connection:
row = connection.execute("SELECT * FROM deals WHERE channel_id = ?", (channel_id,)).fetchone()
return dict(row) if row else None
def create_ticket(guild_id, channel_id, owner_id):
with database() as connection:
connection.execute(
"INSERT INTO tickets (guild_id, channel_id, owner_id, status) VALUES (?, ?, ?, 'open')",
(guild_id, channel_id, owner_id),
)
def get_ticket(channel_id):
with database() as connection:
row = connection.execute("SELECT * FROM tickets WHERE channel_id = ?", (channel_id,)).fetchone()
return dict(row) if row else None
def set_ticket_claim(channel_id, user_id):
with database() as connection:
connection.execute(
"UPDATE tickets SET claimed_by = ? WHERE channel_id = ? AND status = 'open' AND claimed_by IS NULL",
(user_id, channel_id),
)
row = connection.execute("SELECT * FROM tickets WHERE channel_id = ?", (channel_id,)).fetchone()
return dict(row) if row else None
def set_ticket_status(channel_id, status):
with database() as connection:
connection.execute("UPDATE tickets SET status = ? WHERE channel_id = ?", (status, channel_id))
row = connection.execute("SELECT * FROM tickets WHERE channel_id = ?", (channel_id,)).fetchone()
return dict(row) if row else None
def get_open_deals(guild_id):
with database() as connection:
rows = connection.execute(
"SELECT * FROM deals WHERE guild_id = ? AND status NOT IN (?, ?, ?) ORDER BY channel_id DESC LIMIT 20",
(guild_id, *FINAL_STATUSES),
).fetchall()
return [dict(row) for row in rows]
def get_member_deals(guild_id, user_id, include_closed):
with database() as connection:
if include_closed:
rows = connection.execute(
"SELECT * FROM deals WHERE guild_id = ? AND (buyer_id = ? OR seller_id = ?) "
"ORDER BY channel_id DESC LIMIT 20",
(guild_id, user_id, user_id),
).fetchall()
else:
rows = connection.execute(
"SELECT * FROM deals WHERE guild_id = ? AND (buyer_id = ? OR seller_id = ?) "
"AND status NOT IN (?, ?, ?) ORDER BY channel_id DESC LIMIT 20",
(guild_id, user_id, user_id, *FINAL_STATUSES),
).fetchall()
return [dict(row) for row in rows]
def get_deal_counts(guild_id):
with database() as connection:
rows = connection.execute(
"SELECT status, COUNT(*) AS count FROM deals WHERE guild_id = ? GROUP BY status",
(guild_id,),
).fetchall()
return {row["status"]: row["count"] for row in rows}
def update_deal_details(channel_id, details):
with database() as connection:
connection.execute(
"UPDATE deals SET details = ?, status = 'awaiting_agreement', "
"buyer_accepted = 0, seller_accepted = 0, resolution_note = '' WHERE channel_id = ?",
(details, channel_id),
)
row = connection.execute("SELECT * FROM deals WHERE channel_id = ?", (channel_id,)).fetchone()
return dict(row) if row else None
def set_message_id(channel_id, message_id):
with database() as connection:
connection.execute("UPDATE deals SET message_id = ? WHERE channel_id = ?", (message_id, channel_id))
def record_acceptance(channel_id, user_id):
with database() as connection:
deal = connection.execute("SELECT * FROM deals WHERE channel_id = ?", (channel_id,)).fetchone()
if not deal:
return None
column = "buyer_accepted" if user_id == deal["buyer_id"] else "seller_accepted"
connection.execute(f"UPDATE deals SET {column} = 1 WHERE channel_id = ?", (channel_id,))
deal = connection.execute("SELECT * FROM deals WHERE channel_id = ?", (channel_id,)).fetchone()
if deal["buyer_accepted"] and deal["seller_accepted"]:
connection.execute("UPDATE deals SET status = 'active' WHERE channel_id = ?", (channel_id,))
deal = connection.execute("SELECT * FROM deals WHERE channel_id = ?", (channel_id,)).fetchone()
return dict(deal)
def set_deal_status(channel_id, status, note=""):
with database() as connection:
connection.execute(
"UPDATE deals SET status = ?, resolution_note = ? WHERE channel_id = ?",
(status, note, channel_id),
)
row = connection.execute("SELECT * FROM deals WHERE channel_id = ?", (channel_id,)).fetchone()
return dict(row) if row else None
def set_staff_role(guild_id, role_id):
with database() as connection:
connection.execute(
"INSERT INTO guild_settings (guild_id, staff_role_id) VALUES (?, ?) "