TotalFreedomBot/commands/server_commands.py

458 lines
18 KiB
Python
Raw Normal View History

2020-12-08 22:27:01 +00:00
import re
2021-01-07 19:18:25 +00:00
from datetime import datetime
2020-12-02 21:41:20 +00:00
2021-01-07 19:18:25 +00:00
import discord
import requests
2020-10-28 11:47:39 +00:00
from discord.ext import commands
2021-01-07 19:18:25 +00:00
2021-03-29 22:56:38 +00:00
from checks import is_liaison, is_staff, is_senior, is_creative_designer, is_mod_or_has_perms, NoPermission, is_dev, is_gmod_owner, is_smp_owner, notAdminCommand
2021-01-07 19:18:25 +00:00
from functions import hit_endpoint, get_server_status, format_list_entry, read_json
2020-12-08 22:48:54 +00:00
from unicode import clipboard
2020-10-28 11:47:39 +00:00
2021-01-07 19:18:25 +00:00
class ServerCommands(commands.Cog, name="Server Commands"):
2020-10-28 11:47:39 +00:00
def __init__(self, bot):
self.bot = bot
2021-01-04 23:44:57 +00:00
2021-01-04 23:40:43 +00:00
def write_telnet_session(self, server, to_write):
if server == 1:
return self.bot.telnet_object.session.write(to_write)
else:
return self.bot.telnet_object_2.session.write(to_write)
2021-01-04 23:44:57 +00:00
2021-01-04 23:40:43 +00:00
def read_until_telnet(self, to_read, server):
if server == 1:
return self.bot.telnet_object.session.read_until(to_read).decode('utf-8')
else:
return self.bot.telnet_object_2.session.read_until(to_read).decode('utf-8')
2021-01-04 23:44:57 +00:00
2020-10-28 11:47:39 +00:00
@commands.command()
@is_liaison()
async def eventhost(self, ctx, user: discord.Member):
2020-12-08 22:42:29 +00:00
"""Add or remove event host role - liaison only."""
2021-01-07 19:18:25 +00:00
eventhostrole = ctx.guild.get_role(self.bot.event_host)
2020-10-28 11:47:39 +00:00
if eventhostrole in user.roles:
await user.remove_roles(eventhostrole)
2020-10-31 02:02:54 +00:00
await ctx.send(f'```Succesfully took {eventhostrole.name} from {user.name}```')
2020-10-28 11:47:39 +00:00
else:
await user.add_roles(eventhostrole)
2020-10-31 02:02:54 +00:00
await ctx.send(f'```Succesfully added {eventhostrole.name} to {user.name}```')
2020-10-31 02:02:54 +00:00
@commands.command()
@is_creative_designer()
async def masterbuilder(self, ctx, user: discord.Member):
2020-12-08 22:42:29 +00:00
"""Add or remove master builder role - ECD only."""
2021-01-07 19:18:25 +00:00
master_builder_role = ctx.guild.get_role(self.bot.master_builder)
2020-10-31 02:02:54 +00:00
if master_builder_role in user.roles:
await user.remove_roles(master_builder_role)
await ctx.send(f'```Succesfully took {master_builder_role.name} from {user.name}```')
else:
await user.add_roles(master_builder_role)
await ctx.send(f'```Succesfully added {master_builder_role.name} to {user.name}```')
2021-03-29 22:56:38 +00:00
@commands.command()
@is_gmod_owner()
async def gmodstaff(self, ctx, user: discord.Member):
"""Add or remove GMOD Staff role - Manager only."""
gmodstaff_role = ctx.guild.get_role(self.bot.gmodstaff_role_id)
if gmodstaff_role in user.roles:
await user.remove_roles(gmodstaff_role)
await ctx.send(f'```Succesfully took {gmodstaff_role.name} from {user.name}```')
else:
await user.add_roles(gmodstaff_role)
await ctx.send(f'```Succesfully added {gmodstaff_role.name} to {user.name}```')
@commands.command()
@is_smp_owner()
async def smpstaff(self, ctx, user: discord.Member):
"""Add or remove SMP Staff role - Manager only."""
smpstaff_role = ctx.guild.get_role(self.bot.smpstaff_role_id)
if smpstaff_role in user.roles:
await user.remove_roles(smpstaff_role)
await ctx.send(f'```Succesfully took {smpstaff_role.name} from {user.name}```')
else:
await user.add_roles(smpstaff_role)
await ctx.send(f'```Succesfully added {smpstaff_role.name} to {user.name}```')
2020-10-28 11:47:39 +00:00
@commands.command()
@is_staff()
async def serverban(self, ctx, user: discord.Member):
2020-12-08 22:42:29 +00:00
"""Add or remove server banned role."""
2021-01-07 19:18:25 +00:00
serverbannedrole = ctx.guild.get_role(self.bot.server_banned)
2020-10-28 11:47:39 +00:00
if serverbannedrole in user.roles:
await user.remove_roles(serverbannedrole)
await ctx.send(f'Took Server Banned role from {user.name}')
else:
await user.add_roles(serverbannedrole)
await ctx.send(f'Added Server Banned role to {user.name}')
2020-10-28 11:47:39 +00:00
@commands.command()
@is_staff()
async def start(self, ctx):
2020-12-08 22:42:29 +00:00
"""Starts the server."""
2020-11-21 12:52:12 +00:00
em = discord.Embed()
2021-01-04 23:40:43 +00:00
server = 1
if ctx.channel.id == 793632795598913546:
server = 2
2020-11-21 12:52:12 +00:00
try:
2021-01-04 23:40:43 +00:00
attempt = hit_endpoint('start', server)
2020-11-21 12:52:12 +00:00
except Exception as e:
em.title = 'Command error'
2020-11-21 12:52:12 +00:00
em.colour = 0xFF0000
em.description = 'Something went wrong'
2021-03-29 22:56:38 +00:00
print(f'Error while starting freedom-0{server}: {e}')
2020-11-21 12:52:12 +00:00
await ctx.send(embed=em)
else:
if 'error' in attempt.lower():
em.title = 'Command error'
2020-11-21 12:52:12 +00:00
em.colour = 0xFF0000
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server}: {attempt}'
2020-11-21 12:52:12 +00:00
await ctx.send(embed=em)
else:
em.title = 'Success'
em.colour = 0x00FF00
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server}: {attempt}'
2020-11-21 12:52:12 +00:00
await ctx.send(embed=em)
2020-11-21 12:52:12 +00:00
@commands.command()
async def uptime(self, ctx):
2020-12-08 22:42:29 +00:00
"""Returns the uptime of the VPS."""
2020-11-21 12:52:12 +00:00
em = discord.Embed()
em.title = 'VPS Uptime Information'
2021-03-29 22:56:38 +00:00
try:
attempt = hit_endpoint('uptime')
except Exception as e:
em.title = 'Command error'
em.colour = 0xFF0000
print(f'Error while starting freedom-0{server}: {e}')
em.description = f'Something went wrong'
else:
em.description = attempt
2020-11-21 12:52:12 +00:00
await ctx.send(embed=em)
2020-10-28 11:47:39 +00:00
@commands.command()
@is_staff()
async def stop(self, ctx):
2020-12-08 22:42:29 +00:00
"""Stops the server."""
2020-10-30 13:57:59 +00:00
em = discord.Embed()
2021-01-04 23:40:43 +00:00
server = 1
if ctx.channel.id == 793632795598913546:
server = 2
2020-10-30 13:57:59 +00:00
try:
2021-03-29 22:56:38 +00:00
tempem = discord.Embed()
tempem.title = "Command sending"
tempem.description = "Please stand by this could take a minute"
tempem.colour = 0xFFFF00
tempm = await ctx.send(embed = tempem)
attempt = hit_endpoint('stop', server, timeout=30)
2020-11-21 12:52:12 +00:00
except Exception as e:
2021-03-29 22:56:38 +00:00
await tempm.delete()
em.title = 'Command error'
2020-10-30 13:57:59 +00:00
em.colour = 0xFF0000
em.description = 'Something went wrong'
2021-03-29 22:56:38 +00:00
print(f'Error while stopping freedom-0{server}: {e}')
2020-10-30 13:57:59 +00:00
await ctx.send(embed=em)
else:
2021-03-29 22:56:38 +00:00
await tempm.delete()
2020-11-21 12:52:12 +00:00
if 'error' in attempt.lower():
em.title = 'Command error'
2020-11-21 12:52:12 +00:00
em.colour = 0xFF0000
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server}: {attempt}'
2020-11-21 12:52:12 +00:00
await ctx.send(embed=em)
else:
em.title = 'Success'
em.colour = 0x00FF00
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server}: {attempt}'
2020-11-21 12:52:12 +00:00
await ctx.send(embed=em)
2020-10-31 02:02:54 +00:00
@commands.command(aliases=['adminconsole', 'ac'])
@is_staff()
async def telnet(self, ctx, *args):
2020-12-08 22:42:29 +00:00
"""mv, gtfo, kick, mute or warn from discord."""
2020-10-31 02:02:54 +00:00
em = discord.Embed()
2021-01-04 23:40:43 +00:00
server = 1
if ctx.channel.id == 793632795598913546:
server = 2
2020-10-31 02:02:54 +00:00
command = ''
2020-12-02 21:41:51 +00:00
for arg in args:
command += f'{arg} '
2020-10-31 02:02:54 +00:00
try:
2021-01-04 23:44:57 +00:00
if args[0] in ['mute', 'stfu', 'gtfo', 'ban', 'unban', 'unmute', 'smite', 'noob', 'tban', 'tempban', 'warn',
2021-03-29 22:56:38 +00:00
'mv', 'kick', 'cc', 'say', 'autoclear', 'autotp', 'toggle']:
2021-01-04 23:44:57 +00:00
self.write_telnet_session(server,
bytes(command, 'ascii') + b"\r\n")
2021-01-04 23:40:43 +00:00
elif args[0] == 'saconfig':
2020-10-31 15:15:46 +00:00
if args[1] not in ['add', 'remove']:
2021-03-29 22:56:38 +00:00
raise NoPermission(['SACONFIG_EDIT_FROM_ADMIN_CONSOLE'])
2020-10-31 15:15:46 +00:00
else:
2021-01-04 23:44:57 +00:00
self.write_telnet_session(server,
bytes(command, 'ascii') + b"\r\n")
2020-10-31 02:02:54 +00:00
else:
2021-03-29 22:56:38 +00:00
raise notAdminCommand()
2020-10-31 02:02:54 +00:00
except Exception as e:
em.title = 'Command error'
2020-10-31 02:02:54 +00:00
em.colour = 0xFF0000
em.description = f'{e}'
await ctx.send(embed=em)
else:
em.title = 'Success'
em.colour = 0x00FF00
2021-03-29 22:56:38 +00:00
em.description = f'Command sent to freedom-0{server}.'
2020-10-31 02:02:54 +00:00
await ctx.send(embed=em)
2020-10-28 11:47:39 +00:00
@commands.command()
@is_senior()
async def kill(self, ctx):
2020-12-08 22:42:29 +00:00
"""Kills the server."""
2020-10-30 13:57:59 +00:00
em = discord.Embed()
2021-01-04 23:40:43 +00:00
server = 1
if ctx.channel.id == 793632795598913546:
server = 2
2020-10-30 13:57:59 +00:00
try:
2021-01-04 23:40:43 +00:00
attempt = hit_endpoint('kill', server)
2020-11-21 12:52:12 +00:00
except Exception as e:
em.title = 'Command error'
2020-10-30 13:57:59 +00:00
em.colour = 0xFF0000
em.description = 'Something went wrong'
2020-11-21 12:52:12 +00:00
print(f'Error while killing server: {e}')
2020-10-30 13:57:59 +00:00
await ctx.send(embed=em)
else:
2020-11-21 12:52:12 +00:00
if 'error' in attempt.lower():
em.title = 'Command error'
2020-11-21 12:52:12 +00:00
em.colour = 0xFF0000
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server}: {attempt}'
2020-11-21 12:52:12 +00:00
await ctx.send(embed=em)
else:
em.title = 'Success'
em.colour = 0x00FF00
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server}: {attempt}'
2020-11-21 12:52:12 +00:00
await ctx.send(embed=em)
2020-10-28 11:47:39 +00:00
@commands.command()
@is_staff()
async def restart(self, ctx):
2020-12-08 22:42:29 +00:00
"""Restarts the server."""
2020-10-30 13:57:59 +00:00
em = discord.Embed()
2021-01-04 23:40:43 +00:00
server = 1
if ctx.channel.id == 793632795598913546:
server = 2
2020-10-30 13:57:59 +00:00
try:
2021-01-04 23:44:57 +00:00
self.write_telnet_session(server,
bytes('restart', 'ascii') + b"\r\n")
2020-11-21 12:52:12 +00:00
except Exception as e:
em.title = 'Command error'
2020-10-30 13:57:59 +00:00
em.colour = 0xFF0000
em.description = 'Something went wrong'
2021-03-29 22:56:38 +00:00
print(f'Error while restarting freedom-0{server}: {e}')
2020-10-30 13:57:59 +00:00
await ctx.send(embed=em)
else:
em.title = 'Success'
em.colour = 0x00FF00
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server} restarting.'
2020-10-30 13:57:59 +00:00
await ctx.send(embed=em)
2020-10-28 11:47:39 +00:00
@commands.command()
@is_senior()
async def console(self, ctx, *, command):
2020-12-08 22:42:29 +00:00
"""Send a command as console."""
2020-10-30 13:57:59 +00:00
em = discord.Embed()
2021-01-04 23:40:43 +00:00
server = 1
if ctx.channel.id == 793632795598913546:
server = 2
2020-10-30 13:57:59 +00:00
try:
2021-01-04 23:44:57 +00:00
self.write_telnet_session(server,
bytes(command, 'ascii') + b"\r\n")
2020-10-30 13:57:59 +00:00
except Exception as e:
em.title = 'Command error'
2020-10-30 13:57:59 +00:00
em.colour = 0xFF0000
em.description = f'{e}'
await ctx.send(embed=em)
else:
em.title = 'Success'
em.colour = 0x00FF00
2021-03-29 22:56:38 +00:00
em.description = f'Command sent to freedom-0{server}.'
2020-10-30 13:57:59 +00:00
await ctx.send(embed=em)
2020-10-28 11:47:39 +00:00
@commands.command(aliases=['status'])
async def state(self, ctx):
2020-12-08 22:43:43 +00:00
"""Gets the current status of the Server."""
2020-10-28 11:47:39 +00:00
em = discord.Embed()
2021-01-04 23:40:43 +00:00
server = 1
if ctx.channel.id == 793632795598913546:
server = 2
if get_server_status(server):
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server} is online'
2020-12-08 22:32:20 +00:00
em.colour = 0x00FF00
2020-12-08 22:27:01 +00:00
else:
2021-03-29 22:56:38 +00:00
em.description = f'freedom-0{server} is offline'
2020-10-30 13:57:59 +00:00
em.colour = 0xFF0000
2020-10-28 11:47:39 +00:00
await ctx.send(embed=em)
2021-01-04 23:44:57 +00:00
@commands.command(name='list', aliases=['l', 'who', 'lsit'])
2020-11-21 12:52:12 +00:00
async def online(self, ctx):
2020-12-08 22:37:39 +00:00
"""Gives a list of online players."""
2021-03-29 22:56:38 +00:00
if ctx.channel.id == self.bot.gmod_server_chat:
return
2020-10-28 11:47:39 +00:00
em = discord.Embed()
2021-01-04 23:40:43 +00:00
config_file = read_json('config')
if ctx.channel.id == 793632795598913546:
ip = config_file['SERVER_IP_2']
2021-03-29 22:56:38 +00:00
server = 2
2021-01-04 23:40:43 +00:00
else:
ip = config_file['SERVER_IP']
2021-03-29 22:56:38 +00:00
server = 1
2021-01-04 23:40:43 +00:00
port = config_file['PLAYERLIST_PORT']
2021-03-29 22:56:38 +00:00
em.title = f"Player List - freedom-0{server}"
try:
2021-01-04 23:40:43 +00:00
json = requests.get(f"http://{ip}:{port}/list?json=true", timeout=5).json()
2020-10-28 11:47:39 +00:00
if json["online"] == 0:
em.description = "There are no online players"
else:
em.description = f"There are {json['online']} / {json['max']} online players"
2020-12-18 17:00:52 +00:00
ranks = list(json.keys())
2021-01-04 23:44:57 +00:00
2020-12-18 17:00:52 +00:00
entries = []
2021-01-04 23:44:57 +00:00
for rank in ranks:
if rank not in ['max', 'online'] and json[rank]:
2020-12-18 17:00:52 +00:00
rank_fixed = rank.split('_')
for word in range(len(rank_fixed)):
rank_fixed[word] = rank_fixed[word].capitalize()
entries.append(format_list_entry(em, json[rank], f'{" ".join(rank_fixed)}'))
2021-01-04 23:44:57 +00:00
order = ['Owners', 'Executives', 'Developers', 'Senior Admins', 'Admins', 'Master Builders',
'Operators', 'Imposters']
2021-01-07 19:18:25 +00:00
sorted_ranks = [entry for rank in order for entry in entries if entry.name == rank]
2021-01-04 23:44:57 +00:00
2021-01-07 19:18:25 +00:00
for x in sorted_ranks:
2020-12-18 17:00:52 +00:00
em.add_field(name=f'{x.name} ({x.playercount})', value=x.value, inline=False)
2021-01-04 23:44:57 +00:00
2020-12-18 17:00:52 +00:00
except Exception as e:
2020-11-21 12:52:12 +00:00
em.description = 'Server is offline'
2020-12-18 17:00:52 +00:00
print(e)
2020-10-28 11:47:39 +00:00
await ctx.send(embed=em)
2020-10-28 11:47:39 +00:00
@commands.command()
async def ip(self, ctx):
2020-12-08 22:42:29 +00:00
"""Returns the server IP."""
await ctx.send(embed=discord.Embed(description='play.totalfreedom.me', title='Server IP'))
2020-10-28 11:47:39 +00:00
@commands.command()
@is_staff()
async def archivereports(self, ctx):
2020-12-08 22:55:05 +00:00
"""Archive all in-game reports older than 24 hours."""
2020-10-28 11:47:39 +00:00
count = 0
2021-01-07 19:18:25 +00:00
reports_channel = self.bot.get_channel(self.bot.reports_channel_id)
archived_reports_channel = self.bot.get_channel(
2021-01-07 19:18:25 +00:00
self.bot.archived_reports_channel_id)
2020-10-28 11:47:39 +00:00
await ctx.channel.trigger_typing()
async for report in reports_channel.history(limit=100):
try:
embed = report.embeds[0]
except:
await report.delete()
time = embed.timestamp
difference = datetime.now() - time
if difference.days >= 0:
await report.delete()
await archived_reports_channel.send("Message archived because it is older than 24 hours", embed=embed)
count += 1
await ctx.send("Archived **{}** reports that are older than 24 hours".format(count))
2021-01-04 23:44:57 +00:00
2020-12-08 22:27:01 +00:00
@commands.command(aliases=['lag', 'gc'])
async def tps(self, ctx):
2020-12-08 22:42:29 +00:00
"""Lag information regarding the server."""
2020-12-08 22:27:01 +00:00
em = discord.Embed()
em.title = 'Server lag information'
2021-01-04 23:40:43 +00:00
server = 1
if ctx.channel.id == 793632795598913546:
server = 2
if get_server_status(server):
self.write_telnet_session(server,
2021-01-04 23:44:57 +00:00
bytes('lag', 'ascii') + b"\r\n")
2021-01-04 23:40:43 +00:00
self.read_until_telnet(
2021-01-04 23:44:57 +00:00
bytes('Uptime:', 'ascii'), server)
2021-01-04 23:40:43 +00:00
server_uptime = self.read_until_telnet(
2021-01-04 23:44:57 +00:00
bytes('Current TPS =', 'ascii'), server)
2021-01-04 23:40:43 +00:00
server_tps = self.read_until_telnet(
2021-01-04 23:44:57 +00:00
bytes('Maximum memory: ', 'ascii'), server)
2021-01-04 23:40:43 +00:00
maximum_memory = self.read_until_telnet(
2021-01-04 23:44:57 +00:00
bytes('Allocated memory:', 'ascii'), server)
2021-01-04 23:40:43 +00:00
allocated_memory = self.read_until_telnet(
2021-01-04 23:44:57 +00:00
bytes('Free memory:', 'ascii'), server)
2021-01-04 23:40:43 +00:00
free_memory = self.read_until_telnet(
2021-01-04 23:44:57 +00:00
bytes('World "world":', 'ascii'), server)
2020-12-08 22:27:01 +00:00
server_uptime = server_uptime.strip(':Current TPS =')
server_tps = server_tps.strip(':Maximum memory:')
maximum_memory = maximum_memory.strip(':Allocated memory:')
allocated_memory = allocated_memory.strip(':Free memory:')
free_memory = free_memory.strip(':World "world":')
2021-01-04 23:44:57 +00:00
print(
f'TPS: {server_tps} UPTIME: {server_uptime} MAX MEM: {maximum_memory} ALLCTD MEM: {allocated_memory} FREE MEM: {free_memory}')
2020-12-08 22:27:01 +00:00
try:
2021-01-04 23:44:57 +00:00
server_uptime = \
2021-01-07 19:18:25 +00:00
re.match('([0-9]+ days? )?([0-9]+ hours )?([0-9]+ minutes )?([0-6]?[0-9] seconds)', server_uptime)[
0]
2021-01-04 23:40:43 +00:00
server_tps = re.match('[0-2][0-9].?[0-9]*', server_tps)[0]
maximum_memory = re.match('[0-9]+,?[0-9]* MB', maximum_memory)[0]
allocated_memory = re.match('[0-9]+,?[0-9]* MB', allocated_memory)[0]
free_memory = re.match('[0-9]+,?[0-9]* MB', free_memory)[0]
2020-12-08 22:27:01 +00:00
except Exception as e:
em.description = f'Something went wrong: {e}'
em.colour = 0xFF0000
else:
2021-01-04 23:44:57 +00:00
em.add_field(name='TPS', value=server_tps, inline=False)
em.add_field(name='Uptime', value=server_uptime, inline=False)
em.add_field(name='Maximum Memory', value=maximum_memory, inline=False)
em.add_field(name='Allocated Memory', value=allocated_memory, inline=False)
em.add_field(name='Free Memory', value=free_memory, inline=False)
2020-12-08 22:27:01 +00:00
else:
em.description = 'Server is offline'
await ctx.send(embed=em)
2021-01-04 23:44:57 +00:00
2020-10-28 11:47:39 +00:00
@commands.command()
@is_mod_or_has_perms()
async def fixreports(self, ctx):
await ctx.channel.trigger_typing()
2021-01-07 19:18:25 +00:00
reports_channel = self.bot.get_channel(self.bot.reports_channel_id)
2020-10-28 11:47:39 +00:00
messages = await reports_channel.history(limit=500).flatten()
fixed = 0
for message in messages:
if len(message.reactions) == 0 and message.author == message.guild.me:
await message.add_reaction(clipboard)
fixed += 1
await ctx.send(f'Fixed **{fixed}** reports')
2021-03-29 22:56:38 +00:00
@commands.command(aliases=['selfrestart', 'ar'], usage='tf!autorestart [on|off]')
@is_dev()
async def autorestart(self, ctx, *opt):
"""Toggle the auto-restart feature. Usage: tf!autorestart [on|off]"""
em = discord.Embed()
em.title = 'Automatic restart'
if not opt:
self.bot.auto_restart = not self.bot.auto_restart
elif opt[0].lower() in ['on', 'true']:
self.bot.auto_restart = True
elif opt[0].lower() in ['off', 'false']:
self.bot.auto_restart = False
else:
em.description = 'Invalid arguements'
em.colour = 0xFF0000
await ctx.send(embed=em)
return
if self.bot.auto_restart:
em.description = 'Servers will now automatically restart'
em.colour = 0x00FF00
if not self.bot.auto_restart:
em.description = 'Servers will no longer automatically restart'
em.colour = 0xFF0000
await ctx.send(embed=em)
2020-10-28 11:47:39 +00:00
def setup(bot):
bot.add_cog(ServerCommands(bot))