Fix the DMChannel support

This commit is contained in:
OK 2023-04-12 19:38:20 +02:00
parent 203ebe72c1
commit 4cfb6c162e

View File

@ -3,12 +3,12 @@ import argparse
import toml import toml
import discord import discord
import logging import logging
from discord import Message, TextChannel from discord import Message, TextChannel, DMChannel
from discord.ext import commands from discord.ext import commands
from watchdog.observers import Observer from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler from watchdog.events import FileSystemEventHandler
from .ai_responder import AIResponder, AIMessage from .ai_responder import AIResponder, AIMessage
from typing import Optional from typing import Optional, Union
class ConfigFileHandler(FileSystemEventHandler): class ConfigFileHandler(FileSystemEventHandler):
@ -68,7 +68,7 @@ class FjerkroaBot(commands.Bot):
async def on_message(self, message: Message) -> None: async def on_message(self, message: Message) -> None:
if self.user is not None and message.author.id == self.user.id: if self.user is not None and message.author.id == self.user.id:
return return
if not isinstance(message.channel, TextChannel): if not isinstance(message.channel, (TextChannel, DMChannel)):
return return
message_content = str(message.content).strip() message_content = str(message.content).strip()
if len(message_content) < 1: if len(message_content) < 1:
@ -82,8 +82,8 @@ class FjerkroaBot(commands.Bot):
def channel_by_name(self, def channel_by_name(self,
channel_name: Optional[str], channel_name: Optional[str],
fallback_channel: Optional[TextChannel] = None fallback_channel: Optional[Union[TextChannel, DMChannel]] = None
) -> Optional[TextChannel]: ) -> Optional[Union[TextChannel, DMChannel]]:
if channel_name is None: if channel_name is None:
return fallback_channel return fallback_channel
for guild in self.guilds: for guild in self.guilds:
@ -92,11 +92,16 @@ class FjerkroaBot(commands.Bot):
return channel return channel
return fallback_channel return fallback_channel
async def respond(self, message: AIMessage, channel: TextChannel) -> None: async def respond(self,
try: message: AIMessage,
channel: Union[TextChannel, DMChannel]) -> None:
if isinstance(channel, DMChannel):
if channel.recipient is not None:
channel_name = str(channel.recipient.name)
else:
channel_name = str(channel.id)
else:
channel_name = str(channel.name) channel_name = str(channel.name)
except Exception:
channel_name = str(channel.id)
if channel_name in self.config.get('ignore-channels', []) and not message.direct: if channel_name in self.config.get('ignore-channels', []) and not message.direct:
logging.info(f"ignore message {repr(message)} for channel {channel_name}") logging.info(f"ignore message {repr(message)} for channel {channel_name}")
return return