This commit is contained in:
Johnny Gear 2025-11-13 22:03:20 -06:00
parent cef4a1b731
commit df4dbf8df8
6 changed files with 108 additions and 27 deletions

View file

@ -59,7 +59,7 @@ def generate_order():
orders_config = read_config() orders_config = read_config()
if orders_config['orders_probability'] > random.random(): if orders_config['orders_probability'] < random.random():
# No orders today # No orders today
return { } return { }

View file

@ -5,36 +5,58 @@ from util import make_session
from generate import generate_order, generate_punishment from generate import generate_order, generate_punishment
from db import Database from db import Database
from mastodon import Mastodon from mastodon import Mastodon
from telegram import Telegram
from settings import MASTODON_USERNAME, ORDER_TIMEOUT from settings import MASTODON_USERNAME, ORDER_TIMEOUT
from util import order_time
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
async def order_issue(): async def order_issue():
async with make_session() as session:
orders_info = generate_order() orders_info = generate_order()
if 'orders' not in orders_info: if 'orders' not in orders_info:
logger.info("No orders for today") logger.info("No orders for today")
return return
post = "Here are today's orders for @%s - \n\n" % MASTODON_USERNAME orders_str = "\n".join(orders_info['orders'])
due_by = "Proof of compliance is due by %s" % (
(datetime.datetime.combine(
datetime.datetime.today(),
order_time()
) + ORDER_TIMEOUT
).strftime("%H:%M %p")
)
m_post = "Here are today's orders for @%s -\n\n" % MASTODON_USERNAME
if "count" in orders_info and orders_info['count'] > 1: if "count" in orders_info and orders_info['count'] > 1:
post += f"These are the same orders from the last {orders_info['count']} days\n\n" m_post += f"These are the same orders from the last {orders_info['count']} days\n\n"
post += "\n".join(orders_info['orders']) m_post += orders_str + "\n\n"
m_post += due_by
async with make_session() as session:
m = Mastodon(session) m = Mastodon(session)
status = await m.statusPost(post) m_status = await m.statusPost(m_post)
db = Database()
t_post = "Here are your orders -\n\n"
t_post += orders_str + "\n\n"
t_post += due_by + "\n\n"
t_post += m_status['url']
t = Telegram(session)
await t.message_send(t_post)
db = Database()
db.order_status_put( db.order_status_put(
status['id'], m_status['id'],
status['created_at'], m_status['created_at'],
post m_post
) )
async def order_check(): async def order_check():
async with make_session() as session: async with make_session() as session:
m = Mastodon(session) m = Mastodon(session)
t = Telegram(session)
db = Database() db = Database()
outstanding_orders = db.order_status_outstanding() outstanding_orders = db.order_status_outstanding()
@ -61,17 +83,24 @@ async def order_check():
logger.info('Time to issue a punishment for %s' % outstanding_order['created_at']) logger.info('Time to issue a punishment for %s' % outstanding_order['created_at'])
punishment = generate_punishment() punishment = generate_punishment()
punishment_str = "\n".join(punishment)
post = "@%s has failed to post proof of compliance. Punishment is as follows -\n\n" % MASTODON_USERNAME m_post = "@%s has failed to post proof of compliance. Here is the punishment -\n\n" % MASTODON_USERNAME
post += "\n".join(punishment) m_post += punishment_str
punishment_status = await m.statusPost( punishment_status = await m.statusPost(
post, m_post,
in_reply_to_id=outstanding_order['mastodon_id'] in_reply_to_id=outstanding_order['mastodon_id']
) )
t_post = "You failed to show proof of compliance. Here is your punishment -\n\n"
t_post += punishment_str + "\n\n"
t_post += punishment_status['url']
await t.message_send(t_post)
db.punishment_status_put( db.punishment_status_put(
outstanding_order['id'], outstanding_order['id'],
punishment_status['id'], punishment_status['id'],
punishment_status['created_at'], punishment_status['created_at'],
post m_post
) )

View file

@ -7,6 +7,7 @@ from scheduler.asyncio import Scheduler
from settings import TIMEZONE, ORDER_TIME, ORDER_TIMEOUT from settings import TIMEZONE, ORDER_TIME, ORDER_TIMEOUT
from orders import order_issue, order_check from orders import order_issue, order_check
from db import Database from db import Database
from util import order_time
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -19,9 +20,8 @@ class OrderScheduler():
self.scheduler = Scheduler(loop=loop, tzinfo=self.tz) self.scheduler = Scheduler(loop=loop, tzinfo=self.tz)
order_time_arr = list(map(int, ORDER_TIME.split(':'))) order_time_dt = order_time()
order_time = datetime.time(hour=order_time_arr[0], minute=order_time_arr[1], tzinfo=self.tz) self.scheduler.daily(order_time_dt, self.scheduled_order)
self.scheduler.daily(order_time, self.scheduled_order)
logger.info(self.scheduler) logger.info(self.scheduler)

View file

@ -10,6 +10,9 @@ MASTODON_USERNAME = os.environ.get('MASTODON_USERNAME')
MASTODON_INSTANCE = os.environ.get("MASTODON_INSTANCE") MASTODON_INSTANCE = os.environ.get("MASTODON_INSTANCE")
MASTODON_ACCESS_TOKEN = os.environ.get('MASTODON_ACCESS_TOKEN') MASTODON_ACCESS_TOKEN = os.environ.get('MASTODON_ACCESS_TOKEN')
TELEGRAM_API_TOKEN = os.environ.get('TELEGRAM_API_TOKEN')
TELEGRAM_CHAT_ID = os.environ.get('TELEGRAM_CHAT_ID')
SQLITE_DB = os.environ.get('SQLITE_DB', 'db.sqlite3') SQLITE_DB = os.environ.get('SQLITE_DB', 'db.sqlite3')
ORDERS_YML = os.environ.get('ORDERS_YML', 'orders.yml') ORDERS_YML = os.environ.get('ORDERS_YML', 'orders.yml')

35
telegram.py Normal file
View file

@ -0,0 +1,35 @@
import json
import logging
from settings import TELEGRAM_API_TOKEN, TELEGRAM_CHAT_ID
logger = logging.getLogger(__name__)
TELEGRAM_API_URL = 'https://api.telegram.org/bot'
class Telegram:
def __init__(self, aiosession):
if TELEGRAM_API_TOKEN is None:
raise Exception("TELEGRAM_API_TOKEN is required")
self.aiosession = aiosession
async def post(self, request, data):
async with self.aiosession.post('{}{}/{}'.format(
TELEGRAM_API_URL,
TELEGRAM_API_TOKEN,
request
), json=data) as response:
if not response.ok:
logger.error('{} {}'.format(request, response.status))
raise Exception('{} {}'.format(request, response.status))
return await response.json()
async def message_send(self, text):
data = {
'chat_id': TELEGRAM_CHAT_ID,
'text': text
}
return await self.post('sendMessage', data=data)

14
util.py
View file

@ -1,4 +1,18 @@
import aiohttp import aiohttp
import pytz
import datetime
from settings import TIMEZONE, ORDER_TIME
def make_session(): def make_session():
return aiohttp.ClientSession() return aiohttp.ClientSession()
def order_time():
tz = pytz.timezone(TIMEZONE)
order_time_arr = list(map(int, ORDER_TIME.split(':')))
return datetime.time(
hour=order_time_arr[0],
minute=order_time_arr[1],
tzinfo=tz
)