terminal/terminal.py

73 lines
2.1 KiB
Python
Raw Normal View History

2024-10-10 14:19:03 +00:00
import config
import asyncio
import logging
2024-10-10 14:22:26 +00:00
import discord
2024-10-10 14:19:03 +00:00
import subprocess
2024-10-10 14:23:13 +00:00
from discord.ext import commands
from logging.handlers import TimedRotatingFileHandler
2024-10-10 14:19:03 +00:00
2024-10-10 14:21:24 +00:00
TOKEN = config.BOT_TOKEN
2024-10-10 14:19:03 +00:00
USER_ID = config.USER_ID
PREFIX = '$'
2024-10-10 14:27:00 +00:00
intents = discord.Intents.default()
2024-10-10 14:31:55 +00:00
intents.messages = True
intents.dm_messages = True
2024-10-10 14:27:00 +00:00
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
2024-10-10 14:19:03 +00:00
def setup_logging():
logger = logging.getLogger('termlog')
logger.setLevel(logging.INFO)
2024-10-10 14:30:27 +00:00
formatter=logging.Formatter(
'%(asctime)s [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
file_handler = TimedRotatingFileHandler(
2024-10-10 14:19:03 +00:00
'terminal.log',
when='midnight',
interval=1,
backupCount=7,
delay=True
2024-10-10 14:30:27 +00:00
)
file_handler.setFormatter(formatter)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
2024-10-10 14:19:03 +00:00
return logger
logger = setup_logging()
@bot.event
async def on_ready():
logger.info(f'Logged in as {bot.user}')
@bot.command(name='cmd')
async def run_cmd(ctx, *, command: str):
if str(ctx.author.id) == USER_ID:
try:
logger.info(f"Command: {command}")
result = subprocess.run(command, shell=True, capture_output=True, text=True)
output = result.stdout or result.stderr
logger.info(f"Output: {output}")
await ctx.send(f"```{output}```")
except Exception as e:
e = f"Error: {str(e)}"
logger.error(e)
await ctx.send(e)
else:
await ctx.send("You are not authorized to use this command.")
logger.warning(f"Command attempt by unauthorized user {ctx.author.id}.")
async def bot_connect():
while True:
try:
await bot.start(TOKEN)
except Exception as e:
e = str(e)
logger.error(f"Terminal couldn't connect! {e}")
await asyncio.sleep(60)
if __name__ == "__main__":
asyncio.run(bot_connect())