-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
236 lines (195 loc) · 9 KB
/
main.py
File metadata and controls
236 lines (195 loc) · 9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import discord
import dotenv
import random
from datetime import datetime, timedelta
import os
import asyncio
from dataclasses import dataclass, field
from dataclasses_json import dataclass_json
from typing import Tuple, List, Dict, Optional, TYPE_CHECKING
from pairing import History
from util import AddSaveLoad
dotenv.load_dotenv()
TOKEN = os.environ["DISCORD_BOT_TOKEN"]
GUILD_ID = os.environ["GUILD_ID"]
THREAD_ONLY_CATEGORY_ID = int(os.environ["THREAD_ONLY_CATEGORY_ID"])
bot = discord.Bot(intents=discord.Intents.all())
# only ping the user if they asked
def mention_(guild, uid: int, asked=None, always_ping = False):
user = discord.utils.get(guild.members, id=uid)
if always_ping or user.id == asked:
return user.mention
else:
return f"@{user.display_name}"
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
@bot.event
async def on_message(message: discord.Message):
if message.author == bot.user:
return
print(f"[{message.author}]: {message.content}")
if message.content.startswith(".hello"):
await message.channel.send("Hello!")
# create a thread if it's a thread only channel!
if isinstance(message.channel, discord.TextChannel):
if message.channel.category_id == THREAD_ONLY_CATEGORY_ID:
# discord UI glitch when you create a thread too fast, this is a mitigation.
await asyncio.sleep(1)
# or in case of image-only message
name = message.content[:50] or "New Thread"
thread = await message.create_thread(name=name, auto_archive_duration=60)
await thread.send(f"Thread created (thread only channel)")
@bot.slash_command(guild_ids=[GUILD_ID])
async def hello(ctx):
await ctx.respond("Hello!")
# the one on one stuff
@dataclass_json
@dataclass
class WeeklyPairings(AddSaveLoad):
filename = "pairings.json"
channame = "1on1-pairs"
# people who are unpaired
# 2 ways to be on this list:
# there are an odd number
# even number but you already had 1-on-1 with other people/person
unpaired: List[int] = field(default_factory=list)
# people who are paired this week
paired: List[Tuple[int, int]] = field(default_factory=list)
# the `1on1` role is to be autopaired every week
@bot.slash_command(guild_ids=[GUILD_ID])
async def add_1_on_1(ctx: discord.Interaction):
# add 1on1 role to user
role = discord.utils.get(ctx.guild.roles, name="1on1")
await ctx.author.add_roles(role)
await ctx.respond("You have signed up for 1on1s!")
@bot.slash_command(guild_ids=[GUILD_ID])
async def remove_1_on_1(ctx):
role = discord.utils.get(ctx.guild.roles, name="1on1")
await ctx.author.remove_roles(role)
await ctx.respond("You have removed yourself from 1on1s!")
@bot.slash_command(guild_ids=[GUILD_ID])
async def open_to_extra_1_on_1(ctx: discord.Interaction):
# add 1on1filler role to user
role = discord.utils.get(ctx.guild.roles, name="1on1filler")
await ctx.author.add_roles(role)
await ctx.respond("You have signed up to be available for more 1on1s (for example when there are an odd number)!")
@bot.slash_command(guild_ids=[GUILD_ID])
async def remove_extra_1_on_1(ctx: discord.Interaction):
role = discord.utils.get(ctx.guild.roles, name="1on1filler")
await ctx.author.remove_roles(role)
await ctx.respond("You have removed yourself from being available for extra 1on1s!")
@bot.slash_command(guild_ids=[GUILD_ID])
async def show_1on1_signed_up(ctx: discord.Interaction):
# show all users with 1on1 role
role = discord.utils.get(ctx.guild.roles, name="1on1")
users = [member.display_name for member in ctx.guild.members if role in member.roles]
await ctx.respond(f"Users who will get pinged weekly to remind to sign up for 1-on-1s {', '.join(users)}")
async def display_pairs(guild, pairings: WeeklyPairings, user_asked: Optional[int] = None, always_ping=False, ctx=None, channel: discord.TextChannel = None):
if not (bool(ctx) ^ bool(channel)):
raise ValueError("Ctx xor channel must be provided")
# for each pair, get the user from their discriminator and mention them
s = ""
if len(pairings.paired) > 0:
s += "*1on1 pairs:*\n"
for pair in pairings.paired:
s += f"{mention_(guild, pair[0], asked=user_asked, always_ping=always_ping)} — {mention_(guild, pair[1], asked=user_asked, always_ping=always_ping)}\n"
elif len(pairings.unpaired) > 0:
s += "*waiting to be paired:*\n"
for user_id in pairings.unpaired:
s += f"{mention_(guild, user_id, asked=user_asked, always_ping=always_ping)}\n"
else:
s += "No pairings made yet"
if ctx:
await ctx.respond(s)
elif channel:
await channel.send(s)
else:
assert False # we need ctx or channel
@bot.slash_command(guild_ids=[GUILD_ID])
async def show_1on1_pairs(ctx: discord.Interaction):
wps = await WeeklyPairings.load(ctx.guild)
if wps:
await display_pairs(ctx.guild, wps, user_asked=ctx.author.id, ctx=ctx)
else:
await ctx.respond("No pairs found")
async def pair_weekly_users(guild: discord.Guild):
hist = await History.load_or_create_new(guild)
wps = await WeeklyPairings.load(guild)
# current users who have opted in
role = discord.utils.get(guild.roles, name="1on1")
current_opt_in = [member.id for member in guild.members if role in member.roles]
if wps:
# only be including unpaired users who are still opted in
still_opted_in_unpaired = [uid for uid in wps.unpaired if uid in current_opt_in]
# combine with currently opted in users
opt_in = list(set(current_opt_in + still_opted_in_unpaired))
else:
opt_in = current_opt_in
# get filler users
filler_role = discord.utils.get(guild.roles, name="1on1filler")
filler_users = [member.id for member in guild.members if filler_role in member.roles] if filler_role else []
pairs, unpaired = hist.pair_people(opt_in=opt_in, filler_users=filler_users)
wps = WeeklyPairings(unpaired=unpaired, paired=pairs)
c1 = wps.save(guild)
c2 = hist.save(guild)
await asyncio.gather(c1, c2)
return wps
@bot.slash_command(guild_ids=[GUILD_ID])
async def pairme(ctx: discord.Interaction):
hist = await History.load_or_create_new(ctx.guild)
pairs = await WeeklyPairings.load(ctx.guild)
person = ctx.author.id
if any(person in pair for pair in pairs.paired):
# TODO should we allow anyone to just sink all the pairs?
await ctx.respond("You are already paired this week!")
return
# get current filler users
filler_role = discord.utils.get(ctx.guild.roles, name="1on1filler")
filler_users = [member.id for member in ctx.guild.members if filler_role in member.roles] if filler_role else []
unused = [pairs.unpaired, filler_users]
other = hist.pair_person(person, unused)
if other == None:
await ctx.respond("No one to pair with, sorry :(")
return
await hist.save(ctx.guild)
pairs.paired.append((person, other))
await pairs.save(ctx.guild)
await ctx.respond(f"Paired {mention_(ctx.guild, person, always_ping=True)} with {mention_(ctx.guild, other, always_ping=True)}")
@bot.slash_command(guild_ids=[GUILD_ID])
async def pair_1on1s(ctx: discord.Interaction):
if not ctx.author.guild_permissions.administrator:
await ctx.respond("You must be an admin to run this command.")
return
wps = await pair_weekly_users(ctx.guild)
await display_pairs(ctx.guild, wps, ctx=ctx, always_ping=True)
def next_friday():
now = datetime.now()
TIME_ON_FRIDAY_TO_RUN = 15 # UTC, so we don't wake up Americas
# 4 represents Friday, calculating days until the next Friday
days_until_friday = (4 - now.weekday()) % 7
if days_until_friday == 0 and now.hour >= TIME_ON_FRIDAY_TO_RUN:
days_until_friday = 7 # Wait until next Friday
next_friday = now + timedelta(days=days_until_friday)
r = next_friday.replace(hour=TIME_ON_FRIDAY_TO_RUN, minute=0, second=0, microsecond=0) # Set time to 7:00 AM
print(f"running pairs in {r}")
return r
def one_on_one_chan(guild: discord.Guild):
return discord.utils.get(guild.channels, name="1-1s")
# a dict mapping guilds to the message we are listening for reacts on each one
current_messages: Dict[discord.Guild, int] = {}
async def weekly_task():
await bot.wait_until_ready()
for guild in bot.guilds:
while not bot.is_closed():
next_run = next_friday()
amt_to_sleep = (next_run - datetime.now()).total_seconds()
if amt_to_sleep < 30 * 60: # this could get triggered in some weird timezone/daylight savings situations, don't start bot <30mins before TIME_ON_FRIDAY_TO_RUN on friday
continue
await asyncio.sleep(amt_to_sleep)
# get the 1-1s channel
wps = await pair_weekly_users(guild)
chan = one_on_one_chan(guild)
await display_pairs(guild, wps, always_ping=True, channel=chan)
bot.loop.create_task(weekly_task())
bot.run(TOKEN)