sesh-secretary/seshsecretary.py
2023-08-07 11:09:04 +02:00

109 lines
3.1 KiB
Python
Executable File

#!/usr/bin/python
from telegram.ext import Updater, CommandHandler, Filters
import os
from random import randrange
import sys
SAVED_PATH = '/var/lib/seshsecretary/saved.txt'
CHATIDS_PATH = '/var/lib/seshsecretary/chatids.txt'
def _list(update, context):
chat_id = update.effective_chat.id
if not check_chat_id(chat_id):
return
response = ""
with open(SAVED_PATH, "r") as f:
for line in f:
response += line.split()[0] + "\n"
if response == "":
context.bot.send_message(chat_id, "Ingen gemte beskeder :(", 'MARKDOWN')
else:
context.bot.send_message(chat_id, response, 'MARKDOWN')
def random(update, context):
chat_id = update.effective_chat.id
if not check_chat_id(chat_id):
return
with open(SAVED_PATH, "r") as f:
lines = f.readlines()
message = lines[randrange(len(lines))]
message_id = message.split()[1]
from_chat_id = message.split()[2]
context.bot.forward_message(chat_id, from_chat_id, message_id)
def get(update, context):
chat_id = update.effective_chat.id
if not check_chat_id(chat_id):
return
message_id = ""
name = update.message.text.split()[1].lower()
with open(SAVED_PATH, "r") as f:
for line in f:
if name == line.split()[0]:
message_id = line.split()[1]
from_chat_id = line.split()[2]
break
if message_id == "":
update.message.reply_text(
"{} findes ik!".format(name))
else:
context.bot.forward_message(chat_id, from_chat_id, message_id)
def save(update, context):
chat_id = update.effective_chat.id
if not check_chat_id(chat_id):
return
name = update.message.text.split()[1].lower()
message_id = update.message.reply_to_message.message_id
cont = True
with open(SAVED_PATH, "r") as f:
for line in f:
if name == line.split()[0]:
cont = False
break
if cont:
with open(SAVED_PATH, "a") as f:
f.write(name + " " + str(message_id) + " " + str(chat_id) + "\n")
update.message.reply_text(name + " er gemt!")
else:
update.message.reply_text(name + " findes allerede :(")
def main():
if not os.path.isfile(SAVED_PATH):
open(SAVED_PATH, 'a').close()
if not os.path.isfile(CHATIDS_PATH):
sys.exit("No chat id supplied")
token = os.getenv('SESHSECRETARY_TOKEN')
if token is None:
sys.exit("Missing environment variable: SESHSECRETARY_TOKEN")
updater = Updater(token, use_context=True)
updater.dispatcher.add_handler(CommandHandler("list", _list))
updater.dispatcher.add_handler(CommandHandler("get", get))
updater.dispatcher.add_handler(CommandHandler("random", random))
updater.dispatcher.add_handler(CommandHandler("save", save, Filters.reply))
updater.start_polling()
updater.idle()
def check_chat_id(chatid):
with open(CHATIDS_PATH) as f:
lines = f.readlines()
lines = [line.rstrip() for line in lines]
return str(chatid) in lines
if __name__ == '__main__':
main()