17 Commits

16 changed files with 330 additions and 85 deletions
+16
View File
@@ -0,0 +1,16 @@
# Created by venv; see https://docs.python.org/3/library/venv.html
# Python
__pycache__/
.python-version
/venv/
pyvenv.cfg
# IDE specific files
.vscode/
.idea/
# telegram bot token config
telegram_bot_token.cfg
logs/
+7 -85
View File
@@ -1,93 +1,15 @@
# pawhub-telegram-bot
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.fostin.de/SinusFox/pawhub-telegram-bot.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.fostin.de/SinusFox/pawhub-telegram-bot/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
1. Run `chmod +x install.sh run.sh`.
2. Run `install.sh`.
3. Add bot token to `telegram_bot_token.cfg`.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Start bot
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
Run `run.sh`.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
## Source
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
[Telegram Python Bot](https://python-telegram-bot.org/)
+40
View File
@@ -0,0 +1,40 @@
import os
# -------------------------------------------#
# DO NOT TOUCH - will be adjusted on runtime #
# -------------------------------------------#
BASE_DIR = dir_path = os.path.dirname(os.path.realpath(__file__))
# TODO: Avoid Race Conditions on event file edits (file locks?)
# -------------------------------------------#
# Configuration Settings #
# -------------------------------------------#
# General
BOT_NAME = "PawHubBot"
# Logging
LOG_FOLDER_PATH = os.path.abspath(os.path.join(BASE_DIR, '..', 'logs'))
LOG_FILE_NAME = os.path.join(LOG_FOLDER_PATH, 'log.txt')
# Administration
ADMIN_IDS = [
1903773270, # SinusFox
5781850368, # Karatarus
30849386 # Goldwolf
]
# Chats
ALLOWED_CHAT_IDS = [0]
ALLOW_DMS = True
# Events
EVENTS_FOLDER = os.path.join(BASE_DIR, '..','events')
+2
View File
@@ -0,0 +1,2 @@
[telegram]
bot_token = MISSING_TOKEN
+26
View File
@@ -0,0 +1,26 @@
import traceback
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import ContextTypes
from config import config
import user_permissions
import log
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not user_permissions.is_user_admin(update.effective_user.id):
log.warning(chat_id=update.effective_chat.id, message=f"Unauthorized direct message access attempt by user {update.effective_user.id}\n{traceback.format_exc()}")
await update.message.reply_text("You are not authorized to use this bot in this chat.")
return
keyboard = [
[InlineKeyboardButton("Eventmanagement", callback_data='list_event_actions')],
]
await update.message.reply_text(
f"""Willkommen beim {config.BOT_NAME} Admin Interface!
Hier kannst du verschiedene Verwaltungsaufgaben durchführen. Nutze die verfügbaren Befehle, um loszulegen.
(c) SinusFox.dev 2025
""",
reply_markup=InlineKeyboardMarkup(keyboard)
)
+7
View File
@@ -0,0 +1,7 @@
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import configparser
import json
import os
+64
View File
@@ -0,0 +1,64 @@
import os
from config import config
import log
from telegram import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import ContextTypes
import user_permissions
import traceback
os.makedirs(config.EVENTS_FOLDER, exist_ok=True)
async def list_event_actions(update: Update, context: ContextTypes.DEFAULT_TYPE, query: CallbackQuery):
if not user_permissions.is_user_admin(update.effective_user.id):
log.warning(chat_id=update.effective_chat.id, message=f"Unauthorized direct message access attempt by user {update.effective_user.id}\n{traceback.format_exc()}")
await update.message.reply_text("You are not authorized to use this bot in this chat.")
return
keyboard = [
[InlineKeyboardButton("Neues Event anlegen", callback_data='new_event')],
[InlineKeyboardButton("Event bearbeiten", callback_data='edit_event')],
[InlineKeyboardButton("Event löschen", callback_data='delete_event')]
]
await query.message.reply_text(
f'Was möchtest du machen?',
reply_markup=InlineKeyboardMarkup(keyboard)
)
async def new_event(update: Update, context: ContextTypes.DEFAULT_TYPE, query: CallbackQuery):
if not user_permissions.is_user_admin(update.effective_user.id):
log.warning(chat_id=update.effective_chat.id, message=f"Unauthorized direct message access attempt by user {update.effective_user.id}\n{traceback.format_exc()}")
await update.message.reply_text("You are not authorized to use this bot in this chat.")
return
keyboard = [
[InlineKeyboardButton("Anmelden", callback_data='register')],
[InlineKeyboardButton("Abmelden", callback_data='cancelRegister')]
]
await query.message.reply_text(
f'Welches Event möchtest du anpassen?',
reply_markup=InlineKeyboardMarkup(keyboard)
)
async def edit_event(update: Update, context: ContextTypes.DEFAULT_TYPE, query: CallbackQuery):
if not user_permissions.is_user_admin(update.effective_user.id):
log.warning(chat_id=update.effective_chat.id, message=f"Unauthorized direct message access attempt by user {update.effective_user.id}\n{traceback.format_exc()}")
await update.message.reply_text("You are not authorized to use this bot in this chat.")
return
keyboard = [
[InlineKeyboardButton("Anmelden", callback_data='register')],
[InlineKeyboardButton("Abmelden", callback_data='cancelRegister')]
]
await query.message.reply_text(
f'Welches Event möchtest du anpassen?',
reply_markup=InlineKeyboardMarkup(keyboard)
)
# TODO: Implement edit event logic
async def delete_event(update: Update, context: ContextTypes.DEFAULT_TYPE, query: CallbackQuery):
# TODO
pass
+28
View File
@@ -0,0 +1,28 @@
[
{
"date": "",
"time": "",
"custom_message": "",
"signup_deadline": "",
"ordered_food_change_deadline": "",
"ordered_food_change_closed": false,
"location": "",
"organizer_id": 0,
"attendees": [
{
"is_guest": false,
"invited_by_user_id": 0,
"user_id_or_guest_id": 0,
"guest_name": "",
"signed_up": true,
"food_ordered": [
{
"food_item": "",
"price": 0.0,
"quantity": 0
}
]
}
]
}
]
+2
View File
@@ -0,0 +1,2 @@
# TODO
# add and remove foods, custom foods, automatic sum of prices, save to event
+2
View File
@@ -0,0 +1,2 @@
# TODO
# e.g. Nutzer nachtraeglich hinzufuegen? ODer wegen Privatsphaere in dms?
Executable
+29
View File
@@ -0,0 +1,29 @@
# [ Linux installation (CachyOS: Arch, Fish, KDE Wallet) ] #
echo Starting installation for CachyOS (using Arch, Fish Console and KDE Wallet)
# required apps
echo Installing required software. Please enter sudo password.
sudo pacman -S git code # python python-pip # python and pip should be installed already
# git setup
echo Setting up git.
echo Git: What is your user name?
read git_username
echo Git: What is your e-mail address?
read git_email
git config --global user.name "$git_username"
git config --global user.email "$git_email"
echo Enabling storage for git credentials using KDE Wallet
git config --global credential.helper libsecret
# python setup
echo Python setup
python3 -m venv venv
source venv/bin/activate.fish
echo Installing Python Telegram Bot Library
pip install python-telegram-bot
+29
View File
@@ -0,0 +1,29 @@
import os
from config import config
from datetime import datetime
LOG_ID_INFO = 'I'
LOG_ID_WARNING = 'W'
LOG_ID_ERROR = 'E'
def info(chat_id: str, message: str) -> None:
log_line = format_message(LOG_ID_INFO, chat_id, message)
write_log(log_line)
def warning(chat_id: str, message: str) -> None:
log_line = format_message(LOG_ID_WARNING, chat_id, message)
write_log(log_line)
def error(chat_id: str, message: str, stack_trace: str) -> None:
log_line = format_message(LOG_ID_ERROR, chat_id, message)
log_line += f'\nStack Trace:\n{stack_trace}'
write_log(log_line)
def format_message (log_id: str, chat_id: str, message: str) -> str:
return f'{datetime.now().strftime("%Y-%m-%d @ %H:%M")} | {config.BOT_NAME} | {log_id} | {message}'
def write_log(log_line: str):
os.makedirs(config.LOG_FOLDER_PATH, exist_ok=True)
with open(os.path.join(config.LOG_FOLDER_PATH, config.LOG_FILE_NAME), 'a', encoding='utf-8') as log_file:
log_file.write(log_line + '\n')
print(log_line)
+65
View File
@@ -0,0 +1,65 @@
import signal
import sys
import traceback
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, CallbackQueryHandler, Application
import configparser
import direct_message_commands
import event_management
import log
from errors import *
from log import *
config = configparser.ConfigParser()
config.read('config/telegram_bot_token.cfg')
print("Configs loaded.")
def handle_signal(signal, frame):
log.info(chat_id="system", message="Shutdown command received. Stopping service...")
sys.exit(0)
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
async def button_callback_query(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
try:
# Event Management
if query.data == "list_event_actions":
await event_management.list_event_actions(update, context, query)
return
if query.data == "edit_event":
await event_management.edit_event(update, context, query)
return
if query.data == "delete_event":
await event_management.delete_event(update, context, query)
return
if query.data == "new_event":
await event_management.new_event(update, context, query)
return
except Exception as e:
log.error(chat_id=update.effective_chat.id, message=f"Error handling button callback query: {e}", stack_trace=traceback.format_exc())
await update.effective_message.reply_text(f'Leider gab es einen Fehler. Bitte melde die Uhrzeit bei den Admins: {datetime.now().strftime("%Y-%m-%d @ %H:%M")}.')
def main():
log.info(chat_id="system", message="Registering bot commands and starting service...")
app = ApplicationBuilder().token(config['telegram']['bot_token']).build()
# DM commands
app.add_handler(CommandHandler("start", direct_message_commands.start))
# Event management
app.add_handler(CommandHandler("newEvent", event_management.new_event))
# buttons
app.add_handler(CallbackQueryHandler(button_callback_query))
log.info(chat_id="system", message="Service started")
app.run_polling()
if __name__ == "__main__":
log.info(chat_id="system", message="Starting service...")
main()
log.info(chat_id="system", message="Service stopped.")
Executable
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
# start python bot
fish -c 'source venv/bin/activate.fish; python pawhub-bot.py'
+2
View File
@@ -0,0 +1,2 @@
# TODO
# Add and remove users from event, but only set a flag configuring them as "attending" or "not attending" when "deletion"
+7
View File
@@ -0,0 +1,7 @@
from config import config
def is_user_admin(user_id: int) -> bool:
return user_id in config.ADMIN_IDS
def is_chat_allowed(chat_id: int) -> bool:
return chat_id in config.ALLOWED_CHAT_IDS