Skip to content

Commit

Permalink
change structure, introduce library folder
Browse files Browse the repository at this point in the history
It seems that I cannot import library functions to the main codebase
if they're together with the bot object in one file. The bot object
apparently does some global magic, some connections etc., which clash
with whatever my code does. Better to keep bot setup and library
functions separate. That way I can only import library functions
without running commands.Bot()
  • Loading branch information
honzajavorek committed May 24, 2023
1 parent 6012910 commit c57b901
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 59 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,6 @@ dmypy.json

# Pyre type checker
.pyre/

# Library
!juniorguru_chick/lib/
67 changes: 11 additions & 56 deletions juniorguru_chick/bot.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import re
import os
import asyncio
from datetime import datetime
import logging

import discord
from discord.ext import commands

from juniorguru_chick.intro_emojis import choose_intro_emojis
from juniorguru_chick.lib.intro_emojis import choose_intro_emojis
from juniorguru_chick.lib.threads import is_thread_created, fetch_starting_message, create_thread, ensure_thread_name, add_members_with_role


DAYS = ["Pondělní", "Úterní", "Středeční",
"Čtvrteční", "Páteční", "Sobotní", "Nedělní"]

GUILD_ID = int(os.getenv('GUILD_ID', '769966886598737931'))

GREETER_ROLE_ID = 1062755787153358879
Expand Down Expand Up @@ -80,16 +76,17 @@ async def on_thread_create(thread: discord.Thread) -> None:
if not starting_message:
logger.warning(f"Thread {thread.name!r} has no starting message, skipping")
return
is_bot = starting_message.author == bot.user

if channel_name == "ahoj":
await handle_intro_thread(bot, starting_message, thread)
await handle_intro_thread(starting_message, thread, is_bot)
elif channel_name == "práce-inzeráty":
await handle_job_posting_thread(bot, starting_message, thread)
await handle_job_posting_thread(starting_message, thread, is_bot)
elif channel_name == "práce-hledám":
await handle_candidate_thread(bot, starting_message, thread)
await handle_candidate_thread(starting_message, thread, is_bot)


async def handle_intro_thread(bot: discord.Bot, starting_message: discord.Message, thread: discord.Thread) -> None:
async def handle_intro_thread(starting_message: discord.Message, thread: discord.Thread, is_bot: bool) -> None:
emojis = choose_intro_emojis(starting_message.content)
logger.info(f"Processing thread {thread.name!r} (reacting with {emojis!r} and more…)")
tasks = [ensure_thread_name(thread, INTRO_THREAD_NAME_TEMPLATE),
Expand All @@ -98,59 +95,17 @@ async def handle_intro_thread(bot: discord.Bot, starting_message: discord.Messag
await asyncio.gather(*tasks)


async def handle_job_posting_thread(bot: discord.Bot, starting_message: discord.Message, thread: discord.Thread) -> None:
if starting_message.author == bot.user:
async def handle_job_posting_thread(starting_message: discord.Message, thread: discord.Thread, is_bot: bool) -> None:
if is_bot:
logger.info("Message sent by the bot itself, skipping")
return
logger.info(f"Processing thread {thread.name!r} (reacting with ĎK)")
await starting_message.add_reaction("<:dk:842727526736068609>")


async def handle_candidate_thread(bot: discord.Bot, starting_message: discord.Message, thread: discord.Thread) -> None:
if starting_message.author == bot.user:
async def handle_candidate_thread(starting_message: discord.Message, thread: discord.Thread, is_bot: bool) -> None:
if is_bot:
logger.info("Message sent by the bot itself, skipping")
return
logger.info(f"Processing thread {thread.name!r} (reacting with 👍)")
await starting_message.add_reaction("👍")


def is_thread_created(message: discord.Message) -> bool:
"""Checks if given message is a system 'thread created' announcement"""
return message.type == discord.MessageType.thread_created


async def fetch_starting_message(thread: discord.Thread) -> discord.Message | None:
"""Returns the starting message of given thread"""
if thread.starting_message:
return thread.starting_message
try:
# thread.starting_message is often None although the thread
# has a starting message, so try to fetch it manually
return await thread.fetch_message(thread.id)
except discord.errors.NotFound:
return None


async def create_thread(message: discord.Message, name_template) -> discord.Thread:
"""Creates a new thread for given message"""
weekday = datetime.now().weekday()
name = name_template.format(weekday=DAYS[weekday], author=message.author.display_name)
return await message.create_thread(name=name)


async def ensure_thread_name(thread: discord.Thread, name_template) -> str | None:
"""Ensures given thread has a name"""
starting_message = await fetch_starting_message(thread)
if starting_message:
weekday = datetime.now().weekday()
name = name_template.format(weekday=DAYS[weekday], author=starting_message.author.display_name)
if thread.name != name:
await thread.edit(name=name)
return name
else:
return None


async def add_members_with_role(thread: discord.Thread, role_id: int) -> None:
"""Adds members of given role to given thread"""
await thread.send(f"<@&{role_id}>", delete_after=0, silent=True)
Empty file.
File renamed without changes.
49 changes: 49 additions & 0 deletions juniorguru_chick/lib/threads.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from datetime import datetime

import discord


DAYS = ["Pondělní", "Úterní", "Středeční",
"Čtvrteční", "Páteční", "Sobotní", "Nedělní"]


def is_thread_created(message: discord.Message) -> bool:
"""Checks if given message is a system 'thread created' announcement"""
return message.type == discord.MessageType.thread_created


async def fetch_starting_message(thread: discord.Thread) -> discord.Message | None:
"""Returns the starting message of given thread"""
if thread.starting_message:
return thread.starting_message
try:
# thread.starting_message is often None although the thread
# has a starting message, so try to fetch it manually
return await thread.fetch_message(thread.id)
except discord.errors.NotFound:
return None


async def create_thread(message: discord.Message, name_template) -> discord.Thread:
"""Creates a new thread for given message"""
weekday = datetime.now().weekday()
name = name_template.format(weekday=DAYS[weekday], author=message.author.display_name)
return await message.create_thread(name=name)


async def ensure_thread_name(thread: discord.Thread, name_template) -> str | None:
"""Ensures given thread has a name"""
starting_message = await fetch_starting_message(thread)
if starting_message:
weekday = datetime.now().weekday()
name = name_template.format(weekday=DAYS[weekday], author=starting_message.author.display_name)
if thread.name != name:
await thread.edit(name=name)
return name
else:
return None


async def add_members_with_role(thread: discord.Thread, role_id: int) -> None:
"""Adds members of given role to given thread"""
await thread.send(f"<@&{role_id}>", delete_after=0, silent=True)
4 changes: 2 additions & 2 deletions juniorguru_chick/web.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
from datetime import datetime

from aiohttp.web import Application, RouteTableDef, json_response, Request
from aiohttp.web import Application, RouteTableDef, json_response, Request, Response


LAUNCH_AT = datetime.utcnow()
Expand All @@ -15,7 +15,7 @@


@routes.get('/')
async def index(request: Request) -> None:
async def index(request: Request) -> Response:
logger.info(f'Received {request!r}')
return json_response({'status': 'ok',
'launch_at': LAUNCH_AT.isoformat(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from juniorguru_chick.intro_emojis import choose_intro_emojis
from juniorguru_chick.lib.intro_emojis import choose_intro_emojis


def test_choose_intro_emojis():
Expand Down

0 comments on commit c57b901

Please sign in to comment.