Compare commits

..

10 Commits

Author SHA1 Message Date
root
98f2d5f956 added telegraf 2023-10-08 20:54:00 -05:00
root
55966c5cce improved logging output 2023-07-25 00:00:14 -05:00
root
fea9009149 removed host network thing 2023-07-24 23:53:08 -05:00
root
e70d8b4fa0 small tweaks 2023-07-24 23:41:26 -05:00
John Lancaster
e7e3bf9c1f added cli for handling the alive flag 2023-06-11 10:47:35 -05:00
John Lancaster
f11ba04453 increased max line length setting 2023-06-11 10:37:48 -05:00
John Lancaster
bb5a193135 installing kwaylon package in the Dockerfile 2023-06-11 10:19:58 -05:00
John Lancaster
da8b2e83e5 changed the command to use the kwaylon executable 2023-06-11 10:19:42 -05:00
John Lancaster
6a5126e3b7 broke out the logging config 2023-06-11 10:19:29 -05:00
John Lancaster
70b67412d6 rearranged settings 2023-06-11 10:12:31 -05:00
8 changed files with 83 additions and 65 deletions

View File

@@ -4,16 +4,6 @@
"service": "kwaylon",
"workspaceFolder": "/kwaylon",
"shutdownAction": "stopCompose",
// "build": {
// "dockerfile": "./Dockerfile",
// "context": "../"
// },
// "mounts": [
// "source=/etc/localtime,target=/etc/localtime,type=bind",
// "source=/etc/timezone,target=/etc/timezone,type=bind"
// ],
// "workspaceMount": "source=${localWorkspaceFolder}/src,target=/usr/app/src,type=bind",
// "workspaceFolder": "/usr/app/src",
"features": {
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers/features/github-cli:1": {},
@@ -26,17 +16,7 @@
"mhutchie.git-graph",
"ms-python.isort",
"ms-python.autopep8"
],
"settings": {
// "python.editor.defaultFormatter": "ms-python.autopep8",
"[python]": {
"editor.defaultFormatter": "ms-python.python",
"editor.formatOnSave": true
},
"autopep8.args": [
"--max-line-length 120"
]
}
}
}
}

9
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,9 @@
{
"[python]": {
"editor.defaultFormatter": "ms-python.autopep8"
},
"python.formatting.provider": "none",
"autopep8.args": [
"--max-line-length 120"
]
}

View File

@@ -1,12 +1,17 @@
FROM python:latest
RUN apt update && apt install -y bash
RUN python3 -m pip install --upgrade pip
# RUN python3 -m pip install --upgrade pip
RUN mkdir -p /kwaylon/src
WORKDIR /kwaylon
COPY ./requirements.txt ./requirements.txt
RUN --mount=type=cache,mode=0755,target=/root/.cache/pip python3 -m pip install -r ./requirements.txt
RUN --mount=type=cache,mode=0755,target=/root/.cache/pip pip install -r ./requirements.txt
RUN python3 -m nltk.downloader words punkt averaged_perceptron_tagger
RUN mkdir /kwaylon
COPY ./src /kwaylon
WORKDIR /kwaylon
COPY ./src /kwaylon/src
COPY pyproject.toml /kwaylon
RUN pip install -e /kwaylon
CMD [ "kwaylon" ]

View File

@@ -6,7 +6,6 @@ services:
build:
context: ./
restart: unless-stopped
network_mode: host
tty: true
stdin_open: true
volumes:
@@ -14,4 +13,14 @@ services:
- /etc/localtime:/etc/localtime:ro
- /etc/timezone:/etc/timezone:ro
- ./:/kwaylon
command: ["python3", "src/main.py"]
telegraf:
image: telegraf
container_name: telegraf-kwaylon
restart: unless-stopped
user: root:996
volumes:
- /var/run/docker.sock:/var/run/docker.sock
env_file:
- src/.env
command: ["--config", "http://docker-lxc.localdomain:8086/api/v2/telegrafs/0bf0754463950000"]

View File

@@ -20,4 +20,4 @@ dependencies = [
requires-python = ">=3.9"
[project.scripts]
kwaylon = "kwaylon:main"
kwaylon = "kwaylon:cli"

View File

@@ -2,25 +2,59 @@ import asyncio
import logging
import os
import click
from dotenv import load_dotenv
from rich.console import Console
from rich.highlighter import NullHighlighter
from rich.logging import RichHandler
from .jokes import GifJoke, Joke
from .kwaylon import Kwaylon
from .reactions import ReactionData
def main(token_var: str = 'DISCORD_TOKEN'):
load_dotenv()
def init_logging(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'
logging.basicConfig(
level=log_level,
format=log_format,
datefmt=dt_fmt,
handlers=[rich_handler]
)
logging.getLogger('discord').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.INFO)
def main(token_var: str = 'DISCORD_TOKEN', alive_flag: bool = False):
loop = asyncio.new_event_loop()
loop.create_task(
Kwaylon.create_and_start(
os.getenv(token_var),
logging.DEBUG
logging.DEBUG,
alive_flag
)
)
logging.getLogger('discord').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.INFO)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
@click.command()
@click.option('-a', '--alive', required=False, default=False, is_flag=True)
def cli(alive: bool):
load_dotenv()
init_logging(logging.DEBUG)
logging.debug(f'Starting from [bold red]Kwaylon CLI[/]')
main(token_var='DISCORD_TOKEN', alive_flag=alive)

View File

@@ -27,8 +27,8 @@ class GifJoke(Joke):
if hasattr(self, 'chance'):
roll = random.random()
if roll > self.chance:
LOGGER.info(f'Roll was too high {roll:.2f} > {self.chance:.2f}')
LOGGER.info(f'{message.author.display_name}\'s roll was too high {roll:.2f} > {self.chance:.2f}')
return
else:
LOGGER.info(f'Passed roll threshold {roll:.2f} <= {self.chance:.2f}')
LOGGER.info(f'{message.author.display_name} passed roll threshold {roll:.2f} <= {self.chance:.2f}')
await message.reply(self.url)

View File

@@ -1,7 +1,4 @@
import asyncio
import logging
import os
import re
from pathlib import Path
from typing import AsyncIterator, List
@@ -10,9 +7,6 @@ import pandas as pd
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
@@ -25,6 +19,8 @@ _log = logging.getLogger(__name__)
class Kwaylon(Client):
im_alive_flag: bool
def __init__(self, limit: int = 5000, days: int = 30, db_path: Path = None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.jokes = list(jokes.collect_jokes())
@@ -41,34 +37,19 @@ class Kwaylon(Client):
self.robotics_facility: TextChannel = await self.fetch_channel(ROBOTICS_FACILITY_ID)
self.robotics_facility_dev: TextChannel = await self.fetch_channel(DEV_ROBOTICS_FACILITY_ID)
self.kaylon_emoji: Emoji = utils.get(self.emojis, name='kaylon')
if self.im_alive_flag:
# await alive(self.robotics_facility)
_log.info(
'[bold bright_green]Done[/][bright_black], laying in wait...[/]')
await alive(self.robotics_facility_dev)
_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]
)
async def create_and_start(cls, token: str, log_level: int = logging.INFO, alive: bool = False):
intents = Intents.default()
intents.message_content = True
client = cls(intents=intents)
client.im_alive_flag = alive
@client.event
async def on_ready():