65 lines
2.5 KiB
Python
65 lines
2.5 KiB
Python
# plugins/cron.py
|
|
|
|
import sqlite3
|
|
from crontab import CronTab
|
|
import simplematrixbotlib as botlib
|
|
|
|
# Database connection and cursor
|
|
conn = sqlite3.connect('cron.db')
|
|
cursor = conn.cursor()
|
|
|
|
# Create table if not exists
|
|
cursor.execute('''CREATE TABLE IF NOT EXISTS cron (
|
|
room_id TEXT,
|
|
cron_entry TEXT,
|
|
command TEXT
|
|
)''')
|
|
conn.commit()
|
|
|
|
async def handle_command(room, message, bot, prefix, config):
|
|
match = botlib.MessageMatch(room, message, bot, prefix)
|
|
if match.is_not_from_this_bot() and match.prefix() and match.command("cron"):
|
|
args = match.args()
|
|
if len(args) >= 4:
|
|
action = args[0]
|
|
room_id = args[1]
|
|
cron_entry = ' '.join(args[2:-1])
|
|
command = args[-1]
|
|
if action == "add":
|
|
add_cron(room_id, cron_entry, command)
|
|
await bot.api.send_text_message(room.room_id, f"Cron added successfully")
|
|
elif action == "remove":
|
|
remove_cron(room_id, command)
|
|
await bot.api.send_text_message(room.room_id, f"Cron removed successfully")
|
|
else:
|
|
await bot.api.send_text_message(room.room_id, "Usage: !cron add|remove room_id cron_entry command")
|
|
|
|
def add_cron(room_id, cron_entry, command):
|
|
# Check if the cron entry already exists in the database for the given room_id and command
|
|
cursor.execute('SELECT * FROM cron WHERE room_id=? AND command=? AND cron_entry=?', (room_id, command, cron_entry))
|
|
existing_entry = cursor.fetchone()
|
|
if existing_entry:
|
|
return # Cron entry already exists, do not add duplicate
|
|
|
|
# Insert the cron entry into the database
|
|
cursor.execute('INSERT INTO cron (room_id, cron_entry, command) VALUES (?, ?, ?)', (room_id, cron_entry, command))
|
|
conn.commit()
|
|
|
|
def remove_cron(room_id, command):
|
|
cursor.execute('DELETE FROM cron WHERE room_id=? AND command=?', (room_id, command))
|
|
conn.commit()
|
|
|
|
async def run_cron_jobs(bot):
|
|
cron = CronTab()
|
|
for job in cron:
|
|
cron_entry = str(job)
|
|
for row in cursor.execute('SELECT * FROM cron WHERE cron_entry=?', (cron_entry,)):
|
|
room_id, _, command = row
|
|
room = await bot.api.get_room_by_id(room_id)
|
|
if room:
|
|
plugin_name = command.split()[0].replace(prefix, '') # Extract plugin name
|
|
plugin_module = bot.plugins.get(plugin_name)
|
|
if plugin_module:
|
|
await plugin_module.handle_command(room, None, bot, prefix, config)
|
|
|