Files
bot.py
requirements.txt
Code
2 211
bot.py
import asyncio
import logging
import os
import random
from typing import Dict, List, 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)
logger = logging.getLogger("2v2-bot")
queues: Dict[int, List[discord.Member]] = {}
queue_locks: Dict[int, asyncio.Lock] = {}
async def create_match_channel(
guild: discord.Guild, players: List[discord.Member]
) -> discord.TextChannel:
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False)
}
player_permissions = discord.PermissionOverwrite(
view_channel=True,
send_messages=True,
read_message_history=True,
)
for player in players:
overwrites[player] = player_permissions
if guild.me is not None:
overwrites[guild.me] = discord.PermissionOverwrite(
view_channel=True,
send_messages=True,
read_message_history=True,
manage_channels=True,
)
channel = None
try:
channel = await guild.create_text_channel(
name="2v2-match",
overwrites=overwrites,
reason="A 2v2 matchmaking game was created",
)
shuffled_players = random.sample(players, k=4)
team_one = shuffled_players[:2]
team_two = shuffled_players[2:]
message = (
"**2v2 match found!**\n"
f"**Team 1:** {team_one[0].mention} and {team_one[1].mention}\n"
f"**Team 2:** {team_two[0].mention} and {team_two[1].mention}"
)
await channel.send(
message,
allowed_mentions=discord.AllowedMentions(
users=shuffled_players,
everyone=False,
roles=False,
),
)
return channel
except Exception:
if channel is not None:
try:
await channel.delete(reason="Match setup did not complete")
except discord.HTTPException:
logger.exception("Could not clean up an incomplete match channel")
raise
class MatchmakingView(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
@discord.ui.button(
label="Find 2v2",
style=discord.ButtonStyle.success,
custom_id="matchmaking:find_2v2",
)
async def find_match(
self, interaction: discord.Interaction, button: discord.ui.Button
) -> None:
guild = interaction.guild
if guild is None or not isinstance(interaction.user, discord.Member):
await interaction.response.send_message(
"Use this button in a server, not in a direct message.",
ephemeral=True,
)
return
await interaction.response.defer(ephemeral=True)
member = interaction.user
lock = queue_locks.setdefault(guild.id, asyncio.Lock())
channel: Optional[discord.TextChannel] = None
failure = False
async with lock:
queue = queues.setdefault(guild.id, [])
already_waiting = any(player.id == member.id for player in queue)
if not already_waiting:
queue.append(member)
if len(queue) >= 4:
players = queue[:4]
del queue[:4]
try:
channel = await create_match_channel(guild, players)
except Exception:
logger.exception("Could not create a 2v2 match channel")
queue[0:0] = players
failure = True
else:
position = next(
index + 1
for index, player in enumerate(queue)
if player.id == member.id
)
if failure:
await interaction.followup.send(
"I couldn't create the match channel. Make sure I have the "
"**Manage Channels**, **View Channels**, and **Send Messages** "
"permissions, then press **Find 2v2** again. Your queue is saved.",
ephemeral=True,
)
elif channel is not None:
await interaction.followup.send(
f"Your match is ready: {channel.mention}", ephemeral=True
)
elif already_waiting:
await interaction.followup.send(
f"You're already in the queue ({position}/4).",
ephemeral=True,
)
else:
await interaction.followup.send(
f"You're in the queue ({position}/4). I'll create a private match "
"channel when four players have joined.",
ephemeral=True,
)
class MatchBot(commands.Bot):
async def setup_hook(self) -> None:
self.add_view(MatchmakingView())
bot = MatchBot(command_prefix="!", intents=discord.Intents.default())
commands_synced = False
@bot.tree.command(
name="setup_2v2",
description="Post the button players use to find a 2v2 match",
)
@app_commands.checks.has_permissions(manage_guild=True)
async def setup_2v2(interaction: discord.Interaction) -> None:
embed = discord.Embed(
title="Find a 2v2",
description="Press the button below to join matchmaking. A private match "
"channel is created when four players are ready.",
color=discord.Color.green(),
)
await interaction.response.send_message(embed=embed, view=MatchmakingView())
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction, error: app_commands.AppCommandError
) -> None:
if isinstance(error, app_commands.MissingPermissions):
message = "You need the **Manage Server** permission to set up matchmaking."
else:
logger.error(
"Slash command failed",
exc_info=(type(error), error, error.__traceback__),
)
message = "That command failed. Please try again later."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
@bot.event
async def on_ready() -> None:
global commands_synced
if not commands_synced:
try:
await bot.tree.sync()
commands_synced = True
except discord.HTTPException:
logger.exception("Could not sync slash commands")