Bot can now be used to whitelist people
Signed-off-by: SpagettiFisch <johmewu@gmail.com>
This commit is contained in:
commit
928092e72b
5 changed files with 240 additions and 0 deletions
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/config/
|
||||
/data/
|
||||
/modules/__pycache__
|
||||
/whitelist/
|
||||
38
main.py
Normal file
38
main.py
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import discord
|
||||
|
||||
from modules import init
|
||||
from modules import functions
|
||||
|
||||
from discord.ext import commands
|
||||
from discord.ext import slash
|
||||
|
||||
#init.logger()
|
||||
|
||||
token = init.config().get_token()
|
||||
domain = init.config().get_pterodactyl_domain()
|
||||
apikey = init.config().get_pterodactyl_apikey()
|
||||
|
||||
bot = slash.SlashBot(command_prefix='!', help_command=None)
|
||||
# msg_opt = slash.Option(description="Dein Minecraft Name", , required=True)
|
||||
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
print('Bot wurde gestartet')
|
||||
return
|
||||
|
||||
@bot.slash_cmd(aliases=["hilfe"])
|
||||
async def help(ctx:slash.Context):
|
||||
"Hilfe für alle verwendbaren Befehle"
|
||||
await functions.cmdhelp(ctx)
|
||||
|
||||
@bot.slash_cmd(aliases=["minecraft"], guild_id=1210285934248198244)
|
||||
async def mc(ctx:slash.Context, name:slash.Option(description="Dein Minecraftname", required=True)):
|
||||
"Registriere deinen Minecraft Namen"
|
||||
await functions.cmdmc(ctx, name.strip(), bot)
|
||||
|
||||
@bot.slash_cmd()
|
||||
async def mcname(ctx:slash.Context):
|
||||
"Gibt deinen aktuellen Minecraft Namen an"
|
||||
await functions.cmdmcname(ctx)
|
||||
|
||||
bot.run(token)
|
||||
97
modules/functions.py
Normal file
97
modules/functions.py
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import discord
|
||||
import json
|
||||
import requests
|
||||
import urllib
|
||||
import random
|
||||
|
||||
from os import path
|
||||
from shutil import copyfile
|
||||
from discord.ext import slash
|
||||
|
||||
from modules import init
|
||||
|
||||
con, cur = init.getdb()
|
||||
|
||||
async def cmdhelp(ctx:slash.Context):
|
||||
embed = discord.Embed(title="Hilfe",
|
||||
color=discord.Colour(0x15f00a))
|
||||
embed.add_field(name="/mc [Name]",
|
||||
value="Registriere deinen Minecraft-Account")
|
||||
embed.add_field(name="/mcname",
|
||||
value="Gibt deinen aktuellen Minecraft-Account wieder")
|
||||
await ctx.respond(embed=embed, ephemeral=True)
|
||||
return
|
||||
|
||||
async def cmdmc(ctx:slash.Context, name:str, client):
|
||||
mcsite = requests.get(f'https://api.mojang.com/users/profiles/minecraft/{name}')
|
||||
mcinfo = mcsite.json()
|
||||
|
||||
if not 'error' in mcinfo:
|
||||
mcinfo = mcsite.json()
|
||||
uuid = mcinfo['id']
|
||||
uuid = f'{uuid[0:8]}-{uuid[8:12]}-{uuid[12:16]}-{uuid[16:20]}-{uuid[20:32]}'
|
||||
|
||||
result = cur.execute(f"SELECT * FROM user WHERE id = '{ctx.author.id}'")
|
||||
result = cur.fetchone()
|
||||
if result:
|
||||
cur.execute(f"UPDATE user SET mcname = '{mcinfo['name']}', uuid = '{uuid}' WHERE id = {ctx.author.id}")
|
||||
await ctx.respond(f'Dein Minecraftname **{name}** wurde erfolgreich aktualisiert.')
|
||||
else:
|
||||
cur.execute(f"INSERT INTO user VALUES ({ctx.author.id}, '{ctx.author.nick}', '{ctx.author.avatar_url}', '{mcinfo['name']}', '{uuid}', {True})")
|
||||
await ctx.respond(f'Dein Minecraftname **{name}** wurde erfolgreich hinzugefügt.')
|
||||
con.commit()
|
||||
await syncWhitelist()
|
||||
else:
|
||||
await ctx.respond(f'Der Minecraftname **{name}** existiert nicht.', ephemeral=True)
|
||||
|
||||
async def cmdmcname(ctx:slash.Context):
|
||||
result = cur.execute(f"SELECT * FROM user WHERE id = '{ctx.author.id}'")
|
||||
result = cur.fetchone()
|
||||
if result:
|
||||
color = random.randrange(0, 2**24)
|
||||
embed = discord.Embed(title=ctx.author,
|
||||
color=discord.Colour(color))
|
||||
embed.add_field(name="Minecraftname:",
|
||||
value=result[3])
|
||||
embed.set_image(url=result[2])
|
||||
await ctx.respond(embed=embed, ephemeral=True)
|
||||
else:
|
||||
await ctx.respond('Du hast deinen Minecraftnamen noch nicht hinzugefügt. Nutze `/mc [name]` um ihn hinzuzufügen.', ephemeral=True)
|
||||
|
||||
async def syncWhitelist():
|
||||
results = cur.execute("SELECT mcname, uuid, iswhitelisted FROM user")
|
||||
results = cur.fetchall()
|
||||
whitelist = []
|
||||
|
||||
for result in results:
|
||||
if result[2]:
|
||||
whitelist.append({
|
||||
'uuid': result[1],
|
||||
'name': result[0]
|
||||
})
|
||||
with open('whitelist/whitelist.json', 'w') as outfile:
|
||||
json.dump(whitelist, outfile, indent=2)
|
||||
|
||||
await syncWhitelistFiles()
|
||||
await syncWhitelistPterodactyl(whitelist)
|
||||
|
||||
async def syncWhitelistFiles():
|
||||
paths = open('whitelist/paths.txt', 'r')
|
||||
for line in paths:
|
||||
copyfile('whitelist/whitelist.json', f'{str(line.rstrip())}whitelist.json')
|
||||
paths.close()
|
||||
|
||||
async def syncWhitelistPterodactyl(whitelist):
|
||||
paths = open("whitelist/pterodactyl.txt", "r")
|
||||
for line in paths:
|
||||
parts = line.split(" ")
|
||||
serverid = parts[0]
|
||||
whitelistpath = parts[1]
|
||||
|
||||
await pterodactylWriteFile(serverid, whitelistpath, json.dumps(whitelist), init.config().get_pterodactyl_apikey())
|
||||
paths.close()
|
||||
|
||||
async def pterodactylWriteFile(serverid, path, data, apikey):
|
||||
url = f'{init.config().get_pterodactyl_domain()}api/client/servers/{serverid}/files/write?file={urllib.parse.quote(path)}'
|
||||
requests.post(url, data=data, headers={"Accept": "application/json", "Authorization": f"Bearer {apikey}"})
|
||||
print('Whitelist abgeschickt')
|
||||
37
modules/init.py
Normal file
37
modules/init.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import json
|
||||
import datetime
|
||||
import logging
|
||||
import sqlite3
|
||||
|
||||
class config():
|
||||
def __init__(self):
|
||||
with open('config/config.json') as json_file:
|
||||
jsonstructure = json.load(json_file)
|
||||
for p in jsonstructure['discord']:
|
||||
self.token = p['token']
|
||||
self.pterodactyl_domain = p['pterodactyl_domain']
|
||||
self.pterodactyl_apikey = p['pterodactyl_apikey']
|
||||
|
||||
def get_token(self):
|
||||
return self.token
|
||||
def get_pterodactyl_domain(self):
|
||||
return self.pterodactyl_domain
|
||||
def get_pterodactyl_apikey(self):
|
||||
return self.pterodactyl_apikey
|
||||
|
||||
con = sqlite3.connect('data/database.sqlite')
|
||||
cur = con.cursor()
|
||||
cur.execute("""CREATE TABLE IF NOT EXISTS user (id INT PRIMARY KEY, nickname TEXT, avatar_url TEXT, mcname TEXT, uuid TEXT, iswhitelisted BOOLEAN)""")
|
||||
|
||||
def logger():
|
||||
day = datetime.datetime.now()
|
||||
|
||||
logfile = f'logs/discord_{str(day.year)}_{str(day.month)}_{str(day.day)}.log'
|
||||
logger = logging.getLogger('discord')
|
||||
logger.setLevel(logging.WARNING)
|
||||
handler = logging.FileHandler(filename=logfile, encoding='utf-8', mode='w')
|
||||
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
|
||||
logger.addHandler(handler)
|
||||
|
||||
def getdb():
|
||||
return (con, cur)
|
||||
64
modules/setup.py
Normal file
64
modules/setup.py
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import os
|
||||
import json
|
||||
import sqlite3
|
||||
from os import path
|
||||
import init
|
||||
|
||||
#def checkfiles():
|
||||
|
||||
if not os.path.exists('../logs/'):
|
||||
os.makedirs('../logs/')
|
||||
|
||||
if not path.exists('config/config.json'):
|
||||
jsonstructure = {} # Platzhalter
|
||||
jsonstructure['discord'] = []
|
||||
wronginput = False
|
||||
print("Möchtest du das automatisierte Setup nutzen? y/n")
|
||||
input1 = input()
|
||||
|
||||
if input1.lower().strip() == 'y':
|
||||
print("Bitte geben Sie den Token ein:")
|
||||
token = input()
|
||||
print("Bitte geben Sie die Pterodactyl Domain ein (Form: https://example.com/ | optional):")
|
||||
pterodactyl_domain = input()
|
||||
print("Bitte geben Sie den Pterodactyl API Key ein (optional):")
|
||||
pterodactyl_api_key = input()
|
||||
|
||||
jsonstructure['discord'].append({
|
||||
'token': token,
|
||||
'pterodactyl_domain': pterodactyl_domain,
|
||||
'pterodactyl_apikey': pterodactyl_api_key
|
||||
})
|
||||
|
||||
elif input1.lower().strip() == 'n':
|
||||
|
||||
jsonstructure['discord'].append({
|
||||
'token': 'Platzhalter',
|
||||
'pterodactyl_domain': '',
|
||||
'pterodactyl_apikey': ''
|
||||
})
|
||||
|
||||
else:
|
||||
wronginput = True
|
||||
print("Falsche eingabe")
|
||||
|
||||
if not wronginput:
|
||||
if not os.path.exists('config'):
|
||||
os.mkdir('config')
|
||||
with open('config/config.json', 'w') as outfile:
|
||||
json.dump(jsonstructure, outfile, indent=4)
|
||||
print("Config erfolgreich erzeugt")
|
||||
|
||||
if not os.path.exists('whitelist/paths.txt'):
|
||||
if not os.path.exists('whitelist'):
|
||||
os.mkdir('whitelist')
|
||||
paths = open("whitelist/paths.txt", "a")
|
||||
paths.close()
|
||||
paths = open("whitelist/pterodactyl.txt", "a")
|
||||
paths.close()
|
||||
|
||||
if not os.path.exists('data/database.sqlite'):
|
||||
if not os.path.exists('data'):
|
||||
os.mkdir('data')
|
||||
paths = open("data/database.sqlite", "a")
|
||||
paths.close()
|
||||
Loading…
Add table
Reference in a new issue