Files
.gitignore
bot.py
dashboard.py
database.py
requirements.txt
Code
5 862
bot.py
import asyncio
import io
import logging
import os
import secrets
import sqlite3
from pathlib import Path
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from dashboard import DashboardServer
from database import Database
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("community_voter")
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN", "").strip()
DASHBOARD_PASSWORD = os.getenv("DASHBOARD_PASSWORD", "").strip()
DASHBOARD_SECRET = os.getenv("DASHBOARD_SECRET", "").strip() or secrets.token_urlsafe(48)
class ReviewView(discord.ui.View):
def __init__(self, bot, disabled=False):
super().__init__(timeout=None)
self.bot = bot
for child in self.children:
child.disabled = disabled
async def review(self, interaction: discord.Interaction, approved: bool):
if interaction.guild is None or not interaction.user.guild_permissions.manage_guild:
await interaction.response.send_message(
"Only moderators with Manage Server can review proof.", ephemeral=True
)
return
submission = self.bot.database.get_submission_by_log_message(interaction.message.id)
if submission is None:
await interaction.response.send_message("This review record could not be found.", ephemeral=True)
return
result = self.bot.database.review_submission(
submission["id"], approved, interaction.user.id
)
if result is None:
await interaction.response.send_message(
"This submission has already been reviewed.", ephemeral=True
)
return
embed = discord.Embed.from_dict(interaction.message.embeds[0].to_dict())
status = "✅ Approved — included in the channel results" if approved else "❌ Rejected"
color = discord.Color.green() if approved else discord.Color.red()
embed.color = color
for index, field in enumerate(embed.fields):
if field.name == "Status":
embed.set_field_at(index, name="Status", value=status, inline=False)
break
embed.add_field(name="Reviewed by", value=interaction.user.mention, inline=True)
embed.set_footer(text="Review complete")
await interaction.response.edit_message(
embed=embed,
view=ReviewView(self.bot, disabled=True),
)
if approved:
channel = interaction.guild.get_channel(int(result["channel_id"]))
if isinstance(channel, discord.TextChannel):
try:
await self.bot.refresh_board(interaction.guild, channel)
except (discord.HTTPException, PermissionError):
logger.exception("Could not refresh vote board for channel %s", channel.id)
logger.info(
"Submission %s %s by moderator %s",
submission["id"],
"approved" if approved else "rejected",
interaction.user.id,
)
@discord.ui.button(
label="Approve vote",
style=discord.ButtonStyle.success,
custom_id="community_voter:approve",
emoji="✅",
)
async def approve_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.review(interaction, True)
@discord.ui.button(
label="Reject proof",
style=discord.ButtonStyle.danger,
custom_id="community_voter:reject",
emoji="✖️",
)
async def reject_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.review(interaction, False)
class CommunityBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=discord.Intents.default())
self.database = Database(os.getenv("DATABASE_PATH", "votes.sqlite3"))
self.dashboard = DashboardServer(
self.database,
password=DASHBOARD_PASSWORD,
secret=DASHBOARD_SECRET,
)
self.commands_synced = False
async def setup_hook(self):
self.add_view(ReviewView(self))
await self.dashboard.start()
async def close(self):
await self.dashboard.close()
await super().close()
async def refresh_board(self, guild: discord.Guild, channel: discord.TextChannel):
permissions = channel.permissions_for(guild.me)
if not (permissions.send_messages and permissions.embed_links and permissions.manage_messages):
raise PermissionError(
f"I need Send Messages, Embed Links, and Manage Messages in {channel.mention} "
"to keep the leaderboard pinned."
)
embed = build_board_embed(self.database, guild.id, channel.id)
message_id = self.database.get_board_message(guild.id, channel.id)
message = None
if message_id:
try:
message = await channel.fetch_message(message_id)
except discord.NotFound:
message = None
if message is None:
message = await channel.send(embed=embed)
self.database.set_board_message(guild.id, channel.id, message.id)
else:
await message.edit(embed=embed)
if not message.pinned:
await message.pin(reason="Persistent community voting leaderboard")
return message
def build_board_embed(database: Database, guild_id: int, channel_id: int) -> discord.Embed:
embed = discord.Embed(
title="🏆 Community Auto-Completer Vote",
description=(
"Approved community votes are counted here. Submit your choice, a short reason, "
"and proof with **`/vote submit`**."
),
color=discord.Color.from_rgb(72, 115, 230),
)
results = database.get_channel_results(guild_id, channel_id)
if not results:
embed.add_field(
name="No verified votes yet",
value="Be the first to submit a vote. Results appear here after moderator approval.",
inline=False,
)
else:
for rank, result in enumerate(results[:10], start=1):
reasons = result["reasons"]
detail = f"**{result['votes']}** {'vote' if result['votes'] == 1 else 'votes'}"
if reasons:
examples = "\n".join(
f"↳ {discord.utils.escape_markdown(reason[:140])}"
for reason in reasons
)
detail += f"\n{examples}"
embed.add_field(
name=f"{rank}. {discord.utils.escape_markdown(result['entry'][:200])}",
value=detail[:1024],
inline=False,
)
embed.set_footer(text="Only proof reviewed by server moderators is counted")
return embed
bot = CommunityBot()
vote_group = app_commands.Group(name="vote", description="Cast a verified community vote")
voter_group = app_commands.Group(name="voter", description="Configure the community voting system")
@vote_group.command(name="submit", description="Submit your choice, reason, and purchase proof")
@app_commands.guild_only()
@app_commands.describe(
entry="The auto-completer you prefer",
reason="Why it is your favorite",
proof="A screenshot or image showing that you own or bought it",
)
@app_commands.rename(entry="auto_completer")