lists working
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-04-21 22:05:27 +02:00
parent b5551eb596
commit e9d2582606
7 changed files with 216 additions and 36 deletions

View File

@@ -0,0 +1,8 @@
import logging
class BaseHandler:
logger = logging.getLogger(__name__)
entry_string: str
async def entry_point(self, update, context) -> None:
self.logger.info(f"Chat said: {self.entry_string}")

View File

@@ -4,13 +4,14 @@ from telegram.ext import ConversationHandler, CommandHandler, MessageHandler, fi
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
DATE_CHOICE, DATE_ENTRY, CONTENT = range(3)
from .basehandler import BaseHandler
class JournalHandler:
class JournalHandler(BaseHandler):
def __init__(self, entry_string, models):
self.models = models
self.entry_string = entry_string
self.handler = ConversationHandler(
entry_points=[CommandHandler(entry_string, self.start)],
entry_points=[CommandHandler(entry_string, self.entry_point)],
states={
DATE_CHOICE: [
CallbackQueryHandler(self.date_choice),
@@ -19,8 +20,7 @@ class JournalHandler:
MessageHandler(filters.TEXT, self.date_entry),
],
CONTENT: [
MessageHandler(filters.TEXT, self.content_text),
MessageHandler(filters.ATTACHMENT, self.content_media),
MessageHandler(filters.ALL, self.content_save),
],
},
fallbacks=[],
@@ -29,11 +29,8 @@ class JournalHandler:
self.current_model = None
async def start(self, update, context):
"""Send a message when the command /start is issued."""
print(f"User: {update.message.from_user.id}")
print(f"Chat: {update.message.chat_id}")
async def entry_point(self, update, context):
await super().entry_point(update, context)
if os.getenv("DOCKERIZED", "false") == "true" and os.getenv("CHAT_ID") != str(update.message.chat_id):
await update.message.reply_text("You are not authorized to use this bot")
return ConversationHandler.END
@@ -86,25 +83,23 @@ class JournalHandler:
return CONTENT
async def content_text(self, update, context):
self.current_model.text = update.message.text
self.current_model.author_id = update.message.from_user.id
self.current_model.save()
return ConversationHandler.END
async def content_media(self, update, context):
async def content_save(self, update, context):
self.current_model.author_id = update.message.from_user.id
if update.message.photo:
file = await update.message.effective_attachment[-1].get_file()
if update.message.text:
self.current_model.text = update.message.text
else:
file = await update.message.effective_attachment.get_file()
file_bytes = await file.download_as_bytearray()
file_path = file.file_path
self.current_model.save_media(file_bytes, file_path)
if update.message.photo:
file = await update.message.effective_attachment[-1].get_file()
else:
file = await update.message.effective_attachment.get_file()
file_bytes = await file.download_as_bytearray()
file_path = file.file_path
self.current_model.save_media(file_bytes, file_path)
self.current_model.text = update.message.caption
self.current_model.text = update.message.caption
self.current_model.save()
await update.message.reply_text(f"Saved entry for {self.current_model.date.strftime('%A, %-d. %B %Y')}")
return ConversationHandler.END

View File

@@ -12,13 +12,15 @@ DB_DIR.mkdir(parents=True, exist_ok=True)
NAME, NEW, ACTION, ITEMADD, ITEMREMOVE = range(5)
from ..basehandler import BaseHandler
class ListHandler:
class ListHandler(BaseHandler):
"""Create and edit lists"""
def __init__(self, entry_string, models):
self.models = models
self.entry_string = entry_string
self.handler = ConversationHandler(
entry_points=[CommandHandler(entry_string, self.entry_point)],
states={
@@ -43,6 +45,7 @@ class ListHandler:
async def entry_point(self, update, context) -> None:
await super().entry_point(update, context)
set_db(DB_DIR / f"{update.message.chat_id}.db")
lists = ListModel.select()
keyboard = [[InlineKeyboardButton(k.name, callback_data=f"list-{k.name}")] for k in lists] + \
@@ -121,9 +124,9 @@ class ListHandler:
async def list_remove(self, update, context) -> None:
query = update.callback_query
await query.answer()
sl = ListModel.get(name = self.current_name)
list_object = ListModel.get(name = self.current_name)
keyboard = [[InlineKeyboardButton(k, callback_data=i)] for i,k in enumerate(sl)]
keyboard = [[InlineKeyboardButton(k, callback_data=i)] for i,k in enumerate(list_object.content_list)]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text("Which item would you like to remove?", reply_markup = reply_markup)
@@ -153,7 +156,7 @@ class ListHandler:
await query.answer()
it = ListModel.get(name = self.current_name).content_list
if it:
content = "\n* ".join(it)
content = "·" + "\n· ".join(it)
else:
content = "List empty"
@@ -181,7 +184,7 @@ class ListHandler:
list_object = ListModel.get(name = self.current_name)
old = list_object.content_list
name = old.pop(ind)
self.db_utils.list_update(self.current_name, replace=old)
list_object.content_list = old
keyboard = [[InlineKeyboardButton("Remove another", callback_data="remove"), InlineKeyboardButton("Back to the menu", callback_data="overview")]]
reply_markup = InlineKeyboardMarkup(keyboard)

74
bot/commands/status.py Normal file
View File

@@ -0,0 +1,74 @@
import datetime
import requests
import socket
from telegram.ext import ConversationHandler, CommandHandler, CallbackQueryHandler, ParseMode
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
FIRST = 1
from .basehandler import BaseHandler
class StatusHandler(BaseHandler):
"""Shows a short status of the program."""
def __init__(self, entry_string, models):
self.start_time = datetime.datetime.now()
self.entry_string = entry_string
self.models = models
self.handler = ConversationHandler(
entry_points=[CommandHandler(self.entry_string, self.entry_point)],
states={
FIRST: [
CallbackQueryHandler(self.send_log, pattern="^full$"),
]
},
fallbacks=[CommandHandler('status', self.entry_point)],
)
async def entry_point(self, update, context) -> None:
super().entry_point(update, context)
keyboard = [
[
InlineKeyboardButton("And the log?", callback_data="full"),
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
delta = str(datetime.datetime.now() - self.start_time)
message = "BeebBop, this is Norbit)\n"
try:
ip = requests.get('https://api.ipify.org').text
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(('8.8.8.8', 80))
(addr, port) = s.getsockname()
local_ips = addr
except:
ip = "not fetchable"
local_ips = "not fetchable"
message += "Status: Running 🟢\n"
message += "Uptime: `" + delta[:delta.rfind(".")] + "`\n"
message += "IP (public): `" + ip + "`\n"
message += "IP (private): `" + str(local_ips) + "`\n"
if update.message:
await update.message.reply_text(message, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)
else:
await update._effective_chat.send_message(message, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)
return FIRST
async def send_log(self, update, context) -> None:
query = update.callback_query
wanted = query.data.replace("status-","")
query.answer()
# with open("persistence/server.log") as l:
# query.message.reply_document(l)
await update.message.reply_text("Not implemented yet.")
super().log_activity(read = False, execute = False, send = True)
return ConversationHandler.END

View File

@@ -2,7 +2,7 @@ import os
from telegram.ext import Application
import logging
from commands import journal
from commands import journal #, status
from commands.list import list
import models
@@ -24,6 +24,7 @@ def main() -> None:
application.add_handler(journal.JournalHandler("journal", models).handler)
application.add_handler(list.ListHandler("list", models).handler)
# application.add_handler(status.StatusHandlerl("status", models).handler)
# application.add_handler(CommandHandler("help", help_command))
# on non command i.e message - echo the message on Telegram
# application.add_handler(InlineQueryHandler(inline_query))