moved start logic into Kwaylon class

This commit is contained in:
John Lancaster
2023-06-10 09:49:05 -05:00
parent 750fb6625e
commit c2467e126e
2 changed files with 64 additions and 70 deletions

View File

@@ -1,12 +1,18 @@
import asyncio
import logging
import os
import re
from pathlib import Path
from typing import AsyncIterator, List
import pandas as pd
from discord import (Client, Emoji, Guild, Message, RawReactionActionEvent,
TextChannel, utils)
from discord import (Client, Emoji, Guild, Intents, Message,
RawReactionActionEvent, TextChannel, utils)
from dotenv import load_dotenv
from rich.console import Console
from rich.highlighter import NullHighlighter
from rich.logging import RichHandler
from . import jokes
@@ -36,7 +42,46 @@ class Kwaylon(Client):
self.robotics_facility_dev: TextChannel = await self.fetch_channel(DEV_ROBOTICS_FACILITY_ID)
self.kaylon_emoji: Emoji = utils.get(self.emojis, name='kaylon')
# await alive(self.robotics_facility)
_log.info('[bold bright_green]Done[/][bright_black], laying in wait...[/]')
_log.info(
'[bold bright_green]Done[/][bright_black], laying in wait...[/]')
@classmethod
async def create_and_start(cls, token: str, log_level: int = logging.INFO):
rich_handler = RichHandler(
console=Console(width=150),
highlighter=NullHighlighter(),
markup=True,
rich_tracebacks=True,
tracebacks_suppress=['pandas', 'discord'],
)
dt_fmt = '%Y-%m-%d %I:%M:%S %p'
# https://docs.python.org/3/library/logging.html#logrecord-attributes
log_format = '[magenta]%(name)s[/] [cyan]%(funcName)s[/] %(message)s'
formatter = logging.Formatter(log_format, dt_fmt)
logging.basicConfig(
level=log_level,
format=log_format,
datefmt=dt_fmt,
handlers=[rich_handler]
)
logging.getLogger('discord.http').setLevel(logging.WARNING)
logging.getLogger('discord.gateway').setLevel(logging.WARNING)
intents = Intents.default()
intents.message_content = True
client = cls(intents=intents)
@client.event
async def on_ready():
await client.initialize()
@client.event
async def on_message(message: Message):
await client.handle_message(message)
async with client:
await client.start(token, reconnect=True)
async def handle_message(self, message: Message):
if message.author != self.user:
@@ -53,7 +98,8 @@ class Kwaylon(Client):
try:
await joke.respond(message, self, joke_match)
except Exception as e:
_log.error(f'[bold red]{type(e).__name__}[/] when responding to [cyan1]{type(joke).__name__}[/]')
_log.error(
f'[bold red]{type(e).__name__}[/] when responding to [cyan1]{type(joke).__name__}[/]')
raise
async def read_command(self, message: Message):
@@ -154,6 +200,7 @@ def log_info():
for handler in logger.handlers:
print(f' - {str(handler.__class__)[8:-2]}')
def get_emoji_name(string: str) -> str:
if (m := re.search('<:(?P<name>\w+):(?P<id>\d+)>', string)):
string = m.group('name')

View File

@@ -1,76 +1,23 @@
#!/usr/bin/env python3
#!/usr/local/bin/python
import asyncio
import logging
import os
from datetime import datetime
from pathlib import Path
from discord import Intents, Message
from dotenv import load_dotenv
from rich.console import Console
from rich.highlighter import NullHighlighter
from rich.logging import RichHandler
from kwaylon import Kwaylon
TZ = datetime.now().astimezone().tzinfo
async def save_pictures(client: Kwaylon, dest: Path):
kwargs = dict(
limit=10,
after=datetime(year=2023, month=1, day=1, tzinfo=TZ),
oldest_first=True
)
async for msg in client.msg_gen(**kwargs):
if len(msg.attachments) > 0:
for attachment in msg.attachments:
if attachment.content_type == 'image/jpeg':
filepath = Path(f'/kwaylon/pics/{msg.author.display_name.replace(".", "")}_{msg.created_at.strftime("%Y%m%d_%H%M%S.jpeg")}')
if not filepath.exists():
logging.debug(f'[bold blue]{msg.author.display_name}[/] {msg.clean_content[:200]}')
logging.debug(f'Saving {filepath.name}')
await attachment.save(filepath)
else:
logging.debug(f'Skipping {filepath.name}')
if __name__ == '__main__':
rich_handler = RichHandler(
console=Console(width=150),
highlighter=NullHighlighter(),
markup=True,
rich_tracebacks=True,
tracebacks_suppress=['pandas', 'discord'],
)
dt_fmt = '%Y-%m-%d %I:%M:%S %p'
# https://docs.python.org/3/library/logging.html#logrecord-attributes
log_format = '[magenta]%(name)s[/] [cyan]%(funcName)s[/] %(message)s'
formatter = logging.Formatter(log_format, dt_fmt)
logging.basicConfig(
level=logging.DEBUG,
format=log_format,
datefmt=dt_fmt,
handlers=[rich_handler]
)
intents = Intents.default()
intents.message_content = True
client = Kwaylon(intents=intents)
@client.event
async def on_ready():
await client.initialize()
# https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.history
# await save_pictures(client, Path('/kwaylon/pics'))
@client.event
async def on_message(message: Message):
await client.handle_message(message)
load_dotenv()
client.run(
os.getenv('DISCORD_TOKEN'),
log_handler=rich_handler,
log_formatter=formatter,
log_level=logging.INFO,
)
loop = asyncio.new_event_loop()
loop.create_task(
Kwaylon.create_and_start(
os.getenv('DISCORD_TOKEN'),
logging.DEBUG
)
)
try:
loop.run_forever()
except KeyboardInterrupt:
pass