Files
Discord-Message-Git-Tracker/bot.py
2025-02-06 21:46:32 -08:00

97 lines
3.1 KiB
Python

import os
import discord
from discord.ext import commands
from git import Repo
import datetime
from typing import Set
# Bot setup
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
# Initialize repo and tracked messages
REPO_PATH = os.getenv('REPO_PATH', '.') # Path to your git repository
repo = None
tracked_messages: Set[int] = set()
@bot.event
async def on_ready():
global repo
print(f'{bot.user} has connected to Discord!')
try:
repo = Repo(REPO_PATH)
print(f'Connected to git repository at {REPO_PATH}')
except Exception as e:
print(f'Error connecting to git repository: {e}')
@bot.command(name='track')
async def track_message(ctx, message_id: str):
try:
# Convert message_id to integer
msg_id = int(message_id)
tracked_messages.add(msg_id)
await ctx.send(f'Now tracking message with ID: {msg_id}')
except ValueError:
await ctx.send('Please provide a valid message ID')
@bot.command(name='untrack')
async def untrack_message(ctx, message_id: str):
try:
# Convert message_id to integer
msg_id = int(message_id)
if msg_id in tracked_messages:
tracked_messages.remove(msg_id)
await ctx.send(f'Stopped tracking message with ID: {msg_id}')
else:
await ctx.send('This message was not being tracked')
except ValueError:
await ctx.send('Please provide a valid message ID')
@bot.command(name='list-tracked')
async def list_tracked_messages(ctx):
if tracked_messages:
message = 'Currently tracking these message IDs:\n' + '\n'.join(str(mid) for mid in tracked_messages)
else:
message = 'No messages are currently being tracked'
await ctx.send(message)
@bot.event
async def on_message_edit(before, after):
if before.author.bot or before.id not in tracked_messages:
return
try:
# Create a new branch for the edit
current = repo.active_branch
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
branch_name = f'msg_edit_{timestamp}'
# Create and checkout new branch
new_branch = repo.create_head(branch_name)
new_branch.checkout()
# Create or update the message file
message_file = os.path.join(REPO_PATH, f'message_{before.id}.txt')
with open(message_file, 'w') as f:
f.write(f'Message ID: {before.id}\n')
f.write(f'Channel: {before.channel.name}\n')
f.write(f'Author: {before.author.name}\n')
f.write(f'Last Updated: {timestamp}\n\n')
f.write(after.content)
# Stage and commit the changes
repo.index.add([message_file])
repo.index.commit(f'Update message {before.id} - {timestamp}')
# Switch back to the original branch
current.checkout()
await after.channel.send(f'Changes committed to branch: `{branch_name}`')
except Exception as e:
await after.channel.send(f'Error committing changes: {e}')
# Replace 'YOUR_TOKEN' with your bot token
bot.run(os.getenv('DISCORD_TOKEN'))