Skip to content

Commit

Permalink
fix lookup of the starting message
Browse files Browse the repository at this point in the history
  • Loading branch information
honzajavorek committed May 23, 2023
1 parent c84afd9 commit 08e53d5
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions juniorguru_chick/bot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
from datetime import datetime
import logging
from tracemalloc import start

import discord
from discord.ext import commands
Expand All @@ -21,19 +22,36 @@ def is_thread(message: discord.Message) -> bool:
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) -> None:
"""Creates a new thread for given message"""
weekday = datetime.now().weekday()
name = name_template.format(weekday=DAYS[weekday], author=message.author.display_name)
await message.create_thread(name=name)


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


@bot.event
Expand Down Expand Up @@ -78,9 +96,9 @@ async def on_thread_create(thread: discord.Thread) -> None:
channel_name = thread.parent.name
logger.info(f"Thread created in {channel_name!r}")

starting_message = thread.starting_message
starting_message = await fetch_starting_message(thread)
if not starting_message:
logger.info("Thread has no starting message, skipping")
logger.warning(f"Thread {thread.name} has no starting message, skipping")
return

if channel_name == "ahoj":
Expand Down

0 comments on commit 08e53d5

Please sign in to comment.