Updated to v1.9.3

[8b98361](8b983618f2)
This commit is contained in:
ElBe 2022-11-12 22:15:52 +01:00 committed by GitHub
parent 8b983618f2
commit e58c8c4692
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 567 additions and 526 deletions

View File

@ -1,299 +1,299 @@
''' '''
Discord bot template. Discord bot template.
© by ElBe. © by ElBe.
Version: 1.9 Version: 1.9
''' '''
#Imports #Imports
import discord import discord
from discord import utils from discord import utils
import asyncio import asyncio
import datetime import datetime
import time import time
import logging import logging
import platform import platform
import psutil import psutil
import requests import requests
#Bot modules #Bot modules
import functions import functions
import errors import errors
import commands as create_commands import commands as create_commands
import version as bot_version import version as bot_version
#Check modules and python #Check modules and python
if not int(platform.python_version().replace('.','')) <= 3110: if not int(platform.python_version().replace('.','')) <= 3110:
errors.OutdatedVersionError('Python', '3.11.0 or higher', 'https://python.org') errors.OutdatedVersionError('Python', '3.11.0 or higher', 'https://python.org')
#Start #Start
print('Discord.py Bot') print('Discord.py Bot')
print('----------------------------') print('----------------------------')
print('© by ElBe 2022.') print('© by ElBe 2022.')
print('') print('')
print('Start Informations') print('Start Informations')
print('------------------') print('------------------')
print('Discord version: ' + discord.__version__) print('Discord version: ' + discord.__version__)
print('Bot version: ' + bot_version.version) print('Bot version: ' + bot_version.version)
print('') print('')
print('Starting') print('Starting')
print('--------') print('--------')
#Variables #Variables
bold = '**' bold = '**'
italic = '*' italic = '*'
underline = '_' underline = '_'
stroke = '~~' stroke = '~~'
MISSING = utils.MISSING MISSING = utils.MISSING
#Starttime #Starttime
starttime = time.time() starttime = time.time()
#JSON data #JSON data
try: try:
token = functions.json_module.get_config('Config')['Token'] token = functions.json_module.get_config('Config')['Token']
version = bot_version.version version = bot_version.version
credits = functions.json_module.get_config('Config')['Credits'] credits = functions.json_module.get_config('Config')['Credits']
footer = functions.json_module.get_config('Config')['Footer'] footer = functions.json_module.get_config('Config')['Footer']
memberRole = functions.json_module.get_config('Roles')['Member'] memberRole = functions.json_module.get_config('Roles')['Member']
welcomeChannel = functions.json_module.get_config('Channels')['Welcome'] welcomeChannel = functions.json_module.get_config('Channels')['Welcome']
goodbyeChannel = functions.json_module.get_config('Channels')['Goodbye'] goodbyeChannel = functions.json_module.get_config('Channels')['Goodbye']
commands = functions.json_module.get_config('Commands') commands = functions.json_module.get_config('Commands')
except Exception as e: except Exception as e:
print(functions.console.error('Error while trying to get data from the config file.\n' + str(e))) print(functions.console.error('Error while trying to get data from the config file.\n' + str(e)))
exit() exit()
#Setup #Setup
logging.basicConfig(filename='log.txt', level=logging.INFO) logging.basicConfig(filename='log.txt', level=logging.INFO)
intents = discord.Intents.all() intents = discord.Intents.all()
#Create commands #Create commands
try: try:
if functions.json_module.get_config('Created', 'commands.json') == 0: if functions.json_module.get_config('Created', 'commands.json') == 0:
create_commands create_commands
else: else:
None None
except Exception as e: except Exception as e:
print(functions.console.error('Error while trying to create the commands.\n' + str(e))) print(functions.console.error('Error while trying to create the commands.\n' + str(e)))
exit() exit()
#Main #Main
class Bot(discord.Client): class Bot(discord.Client):
'''Bot.''' '''Bot.'''
async def on_connect(self): async def on_connect(self):
logging.info(str(datetime.datetime.now()) + ' Bot connected to the Discord API.') logging.info(str(datetime.datetime.now()) + ' Bot connected to the Discord API.')
print(functions.console.info('Bot connected to the Discord API.')) print(functions.console.info('Bot connected to the Discord API.'))
async def on_ready(self): async def on_ready(self):
logging.info(str(datetime.datetime.now()) + ' Bot logged in as ' + client.user.name + '.') logging.info(str(datetime.datetime.now()) + ' Bot logged in as ' + client.user.name + '.')
print(functions.console.info('Bot logged in as ' + client.user.name + '.')) print(functions.console.info('Bot logged in as ' + client.user.name + '.'))
print('Guilds: ' + str(client.user.guilds)) print('Guilds: ' + str(client.user.guilds))
print('') print('')
print('Log (Consolebased)') print('Log (Consolebased)')
print('------------------') print('------------------')
while True: while True:
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'/help for help.')) await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'/help for help.'))
await asyncio.sleep(10) await asyncio.sleep(10)
await client.change_presence(activity=discord.Game(name=f'Version {version}')) await client.change_presence(activity=discord.Game(name=f'Version {version}'))
await asyncio.sleep(10) await asyncio.sleep(10)
if credits: if credits:
await client.change_presence(activity=discord.Game(name=' programmed by ElBe.')) await client.change_presence(activity=discord.Game(name=' programmed by ElBe.'))
await asyncio.sleep(10) await asyncio.sleep(10)
async def on_resumed(self): async def on_resumed(self):
logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- Bot resumed session.') logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- Bot resumed session.')
print(functions.console.log('Bot resumed a session.')) print(functions.console.log('Bot resumed a session.'))
async def on_interaction(self, interaction): async def on_interaction(self, interaction):
async def log(text: str): async def log(text: str):
'''Log a text and save it in the logfile and the console.''' '''Log a text and save it in the logfile and the console.'''
logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- ' + str(text)) logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- ' + str(text))
print(functions.console.log(str(text))) print(functions.console.log(str(text)))
if interaction.type == discord.InteractionType.application_command: if interaction.type == discord.InteractionType.application_command:
command_name = str(interaction.data['name']) command_name = str(interaction.data['name'])
await log('Command /' + command_name + ' was used by @' + str(interaction.user) + '.') await log('Command /' + command_name + ' was used by @' + str(interaction.user) + '.')
if command_name == 'ping' and commands['ping']: if command_name == 'ping' and commands['ping']:
pingEmbed = discord.Embed(title='Ping', description='Ping of the bot in ms.') pingEmbed = discord.Embed(title='Ping', description='Ping of the bot in ms.')
pingEmbed.add_field(name='Latency: ', value=str(round(client.latency * 1000)) + ' ms', inline=False) pingEmbed.add_field(name='Latency: ', value=str(round(client.latency * 1000)) + ' ms', inline=False)
pingEmbed.set_thumbnail(url=client.user.avatar.url) pingEmbed.set_thumbnail(url=client.user.avatar.url)
pingEmbed.set_footer(text=footer) pingEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=pingEmbed, ephemeral=True) await interaction.response.send_message(embed=pingEmbed, ephemeral=True)
elif command_name == 'ping' and not commands['ping']: elif command_name == 'ping' and not commands['ping']:
commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.') commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.')
commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url) commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url)
commandDisabledEmbed.set_footer(text=footer) commandDisabledEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True) await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True)
if command_name == 'info' and commands['info']: if command_name == 'info' and commands['info']:
infoEmbed = discord.Embed(title='Information', description='Informations about the bot.') infoEmbed = discord.Embed(title='Information', description='Informations about the bot.')
infoEmbed.add_field(name='Running on: ', value=str(platform.system()) + ' ' + str(platform.release()), inline=False) infoEmbed.add_field(name='Running on: ', value=str(platform.system()) + ' ' + str(platform.release()), inline=False)
infoEmbed.add_field(name='CPU usage: ', value=str(psutil.cpu_percent(2)) + '%', inline=False) infoEmbed.add_field(name='CPU usage: ', value=str(psutil.cpu_percent(2)) + '%', inline=False)
infoEmbed.add_field(name='Uptime: ', value=str(datetime.timedelta(seconds=int(round(time.time()-starttime)))), inline=False) infoEmbed.add_field(name='Uptime: ', value=str(datetime.timedelta(seconds=int(round(time.time()-starttime)))), inline=False)
infoEmbed.set_thumbnail(url=client.user.avatar.url) infoEmbed.set_thumbnail(url=client.user.avatar.url)
infoEmbed.set_footer(text=footer) infoEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=infoEmbed, ephemeral=True) await interaction.response.send_message(embed=infoEmbed, ephemeral=True)
elif command_name == 'info' and not commands['info']: elif command_name == 'info' and not commands['info']:
commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.') commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.')
commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url) commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url)
commandDisabledEmbed.set_footer(text=footer) commandDisabledEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True) await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True)
if command_name == 'stop' and commands['stop']: if command_name == 'stop' and commands['stop']:
if interaction.user.guild_permissions.administrator: if interaction.user.guild_permissions.administrator:
await log('Client stoped.') await log('Client stoped.')
exit() exit()
else: else:
noPermissionsEmbed = discord.Embed(title='Missing permissions', description='You don\'t have permissions to do that.', color=discord.Color.red()) noPermissionsEmbed = discord.Embed(title='Missing permissions', description='You don\'t have permissions to do that.', color=discord.Color.red())
noPermissionsEmbed.set_thumbnail(url=client.user.avatar.url) noPermissionsEmbed.set_thumbnail(url=client.user.avatar.url)
noPermissionsEmbed.set_footer(text=footer) noPermissionsEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=noPermissionsEmbed, ephemeral=True) await interaction.response.send_message(embed=noPermissionsEmbed, ephemeral=True)
elif command_name == 'stop' and not commands['stop']: elif command_name == 'stop' and not commands['stop']:
commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.') commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.')
commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url) commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url)
commandDisabledEmbed.set_footer(text=footer) commandDisabledEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True) await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True)
if command_name == 'help' and commands['help']: if command_name == 'help' and commands['help']:
helpEmbed = discord.Embed(title='Help', description='Help for commands and the usage of the bot.') helpEmbed = discord.Embed(title='Help', description='Help for commands and the usage of the bot.')
helpEmbed.add_field(name='Ping', value='Shows the ping of the bot in ms.', inline=True) helpEmbed.add_field(name='Ping', value='Shows the ping of the bot in ms.', inline=True)
helpEmbed.add_field(name='Info', value='Shows information about the bot.', inline=True) helpEmbed.add_field(name='Info', value='Shows information about the bot.', inline=True)
helpEmbed.add_field(name='Help', value='Shows you help for commands and the usage of the bot.', inline=True) helpEmbed.add_field(name='Help', value='Shows you help for commands and the usage of the bot.', inline=True)
helpEmbed.add_field(name='Kick', value='Kicks a member from the server.', inline=True) helpEmbed.add_field(name='Kick', value='Kicks a member from the server.', inline=True)
helpEmbed.add_field(name='Ban', value='Bans a member from the server.', inline=True) helpEmbed.add_field(name='Ban', value='Bans a member from the server.', inline=True)
helpEmbed.add_field(name='Unban', value='Unbans a member from the server.', inline=True) helpEmbed.add_field(name='Unban', value='Unbans a member from the server.', inline=True)
helpEmbed.add_field(name='more', value='For more help write a direct message to <@!745695237380243457>.', inline=False) helpEmbed.add_field(name='more', value='For more help write a direct message to <@!745695237380243457>.', inline=False)
helpEmbed.set_thumbnail(url=client.user.avatar.url) helpEmbed.set_thumbnail(url=client.user.avatar.url)
helpEmbed.set_footer(text=footer) helpEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=helpEmbed, ephemeral=True) await interaction.response.send_message(embed=helpEmbed, ephemeral=True)
if command_name == 'kick' and commands['kick']: if command_name == 'kick' and commands['kick']:
options = interaction.data['options'] options = interaction.data['options']
if interaction.user.guild_permissions.administrator: if interaction.user.guild_permissions.administrator:
member = options[0]['value'] member = options[0]['value']
member = await interaction.guild.fetch_member(int(member)) member = await interaction.guild.fetch_member(int(member))
reason = options[1]['value'] reason = options[1]['value']
if reason == None: reason = 'Kicked by @' + str(interaction.user) + ' with the /kick command.' if reason == None: reason = 'Kicked by @' + str(interaction.user) + ' with the /kick command.'
await member.kick(reason=reason) await member.kick(reason=reason)
kickEmbed = discord.Embed(title='Kick', description='Succesfully kicked <@!' + options[0]['value'] + '>!') kickEmbed = discord.Embed(title='Kick', description='Succesfully kicked <@!' + options[0]['value'] + '>!')
kickEmbed.set_thumbnail(url=client.user.avatar.url) kickEmbed.set_thumbnail(url=client.user.avatar.url)
kickEmbed.set_footer(text=footer) kickEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=kickEmbed, ephemeral=True) await interaction.response.send_message(embed=kickEmbed, ephemeral=True)
else: else:
noPermissionsEmbed = discord.Embed(title='Missing permissions', description='You don\'t have permissions to do that.', color=discord.Color.red()) noPermissionsEmbed = discord.Embed(title='Missing permissions', description='You don\'t have permissions to do that.', color=discord.Color.red())
noPermissionsEmbed.set_thumbnail(url=client.user.avatar.url) noPermissionsEmbed.set_thumbnail(url=client.user.avatar.url)
noPermissionsEmbed.set_footer(text=footer) noPermissionsEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=noPermissionsEmbed, ephemeral=True) await interaction.response.send_message(embed=noPermissionsEmbed, ephemeral=True)
elif command_name == 'kick' and not commands['kick']: elif command_name == 'kick' and not commands['kick']:
commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.') commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.')
commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url) commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url)
commandDisabledEmbed.set_footer(text=footer) commandDisabledEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True) await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True)
if command_name == 'ban' and commands['ban']: if command_name == 'ban' and commands['ban']:
options = interaction.data['options'] options = interaction.data['options']
if interaction.user.guild_permissions.administrator: if interaction.user.guild_permissions.administrator:
member = options[0]['value'] member = options[0]['value']
member = await interaction.guild.fetch_member(int(member)) member = await interaction.guild.fetch_member(int(member))
reason = options[1]['value'] reason = options[1]['value']
if reason == None: reason = 'Banned by @' + str(interaction.user) + ' with the /ban command.' if reason == None: reason = 'Banned by @' + str(interaction.user) + ' with the /ban command.'
await member.ban(reason=reason) await member.ban(reason=reason)
banEmbed = discord.Embed(title='Ban', description='Succesfully banned <@!' + options[0]['value'] + '>!') banEmbed = discord.Embed(title='Ban', description='Succesfully banned <@!' + options[0]['value'] + '>!')
banEmbed.set_thumbnail(url=client.user.avatar.url) banEmbed.set_thumbnail(url=client.user.avatar.url)
banEmbed.set_footer(text=footer) banEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=banEmbed, ephemeral=True) await interaction.response.send_message(embed=banEmbed, ephemeral=True)
else: else:
noPermissionsEmbed = discord.Embed(title='Missing permissions', description='You don\'t have permissions to do that.', color=discord.Color.red()) noPermissionsEmbed = discord.Embed(title='Missing permissions', description='You don\'t have permissions to do that.', color=discord.Color.red())
noPermissionsEmbed.set_thumbnail(url=client.user.avatar.url) noPermissionsEmbed.set_thumbnail(url=client.user.avatar.url)
noPermissionsEmbed.set_footer(text=footer) noPermissionsEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=noPermissionsEmbed, ephemeral=True) await interaction.response.send_message(embed=noPermissionsEmbed, ephemeral=True)
elif command_name == 'ban' and not commands['ban']: elif command_name == 'ban' and not commands['ban']:
commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.') commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.')
commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url) commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url)
commandDisabledEmbed.set_footer(text=footer) commandDisabledEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True) await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True)
if command_name == 'unban' and commands['unban']: if command_name == 'unban' and commands['unban']:
options = interaction.data['options'] options = interaction.data['options']
if interaction.user.guild_permissions.administrator: if interaction.user.guild_permissions.administrator:
member = options[0]['value'] member = options[0]['value']
member = await client.fetch_user(int(member)) member = await client.fetch_user(int(member))
reason = options[1]['value'] reason = options[1]['value']
if reason == None: reason = 'Unbanned by @' + str(interaction.user) + ' with the /unban command.' if reason == None: reason = 'Unbanned by @' + str(interaction.user) + ' with the /unban command.'
await interaction.guild.unban(member, reason=reason) await interaction.guild.unban(member, reason=reason)
unbanEmbed = discord.Embed(title='Unban', description='Succesfully unbanned <@!' + options[0]['value'] + '>!') unbanEmbed = discord.Embed(title='Unban', description='Succesfully unbanned <@!' + options[0]['value'] + '>!')
unbanEmbed.set_thumbnail(url=client.user.avatar.url) unbanEmbed.set_thumbnail(url=client.user.avatar.url)
unbanEmbed.set_footer(text=footer) unbanEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=unbanEmbed, ephemeral=True) await interaction.response.send_message(embed=unbanEmbed, ephemeral=True)
else: else:
noPermissionsEmbed = discord.Embed(title='Missing permissions', description='You don\'t have permissions to do that.', color=discord.Color.red()) noPermissionsEmbed = discord.Embed(title='Missing permissions', description='You don\'t have permissions to do that.', color=discord.Color.red())
noPermissionsEmbed.set_thumbnail(url=client.user.avatar.url) noPermissionsEmbed.set_thumbnail(url=client.user.avatar.url)
noPermissionsEmbed.set_footer(text=footer) noPermissionsEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=noPermissionsEmbed, ephemeral=True) await interaction.response.send_message(embed=noPermissionsEmbed, ephemeral=True)
elif command_name == 'unban' and not commands['unban']: elif command_name == 'unban' and not commands['unban']:
commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.') commandDisabledEmbed = discord.Embed(title='Command disabled', description='This command was disabled in the bot config file. Ask a member with access to the bot to enable this command.')
commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url) commandDisabledEmbed.set_thumbnail(url=client.user.avatar.url)
commandDisabledEmbed.set_footer(text=footer) commandDisabledEmbed.set_footer(text=footer)
await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True) await interaction.response.send_message(embed=commandDisabledEmbed, ephemeral=True)
async def on_member_join(self, member): async def on_member_join(self, member):
if not welcomeChannel == "": if not welcomeChannel == "":
async def log(text: str): async def log(text: str):
'''Log a text and save it in the logfile and the console.''' '''Log a text and save it in the logfile and the console.'''
logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- ' + str(text)) logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- ' + str(text))
print(functions.console.log(str(text))) print(functions.console.log(str(text)))
if not welcomeChannel == '': if not welcomeChannel == '':
if not member == client.user: if not member == client.user:
channel = discord.utils.get(member.guild.text_channels, name=welcomeChannel) channel = discord.utils.get(member.guild.text_channels, name=welcomeChannel)
joinEmbed = discord.Embed(title='Welcome!', description='Hello <@!' + str(member.id) + f'>! \nThank you for joining {member.guild.name}!') joinEmbed = discord.Embed(title='Welcome!', description='Hello <@!' + str(member.id) + f'>! \nThank you for joining {member.guild.name}!')
joinEmbed.set_thumbnail(url=member.avatar.url) joinEmbed.set_thumbnail(url=member.avatar.url)
joinEmbed.set_footer(text=footer) joinEmbed.set_footer(text=footer)
await channel.send(embed=joinEmbed) await channel.send(embed=joinEmbed)
await member.add_roles(discord.utils.get(member.guild.roles, name=str(member))) await member.add_roles(discord.utils.get(member.guild.roles, name=str(member)))
await log('@' + str(member) + ' joined to ' + str(member.guild.name) + '.') await log('@' + str(member) + ' joined to ' + str(member.guild.name) + '.')
async def on_member_remove(self, member): async def on_member_remove(self, member):
if not goodbyeChannel == "": if not goodbyeChannel == "":
async def log(text: str): async def log(text: str):
'''Log a text and save it in the logfile and the console.''' '''Log a text and save it in the logfile and the console.'''
logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- ' + str(text)) logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- ' + str(text))
print(functions.console.log(str(text))) print(functions.console.log(str(text)))
if not goodbyeChannel == '': if not goodbyeChannel == '':
if not member == client.user: if not member == client.user:
channel = discord.utils.get(member.guild.text_channels, name=goodbyeChannel) channel = discord.utils.get(member.guild.text_channels, name=goodbyeChannel)
leaveEmbed = discord.Embed(title='Goodbye!', description='<@!' + str(member.id) + f'> left {member.guild.name}.') leaveEmbed = discord.Embed(title='Goodbye!', description='<@!' + str(member.id) + f'> left {member.guild.name}.')
leaveEmbed.set_thumbnail(url=member.avatar.url) leaveEmbed.set_thumbnail(url=member.avatar.url)
leaveEmbed.set_footer(text=footer) leaveEmbed.set_footer(text=footer)
await channel.send(embed=leaveEmbed) await channel.send(embed=leaveEmbed)
await log('@' + str(member) + ' left ' + str(member.guild.name) + '.') await log('@' + str(member) + ' left ' + str(member.guild.name) + '.')
async def on_disconnect(self): async def on_disconnect(self):
async def error(text: str): async def error(text: str):
'''Send a error text and save it in the logfile.''' '''Send a error text and save it in the logfile.'''
logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- Error: ' + str(text)) logging.info(str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + ' -- Error: ' + str(text))
print(functions.console.error(str(text))) print(functions.console.error(str(text)))
await error('Bot disconected from discord.') await error('Bot disconected from discord.')
#Run #Run
client = Bot(intents = intents, max_messages=None) client = Bot(intents = intents, max_messages=None)
new_version = str(str(str(requests.get('https://raw.githubusercontent.com/ElBe-Plaq/discord.py-bot-template/main/version.py').text).replace('version = ', '')).replace('\n', '')).replace('\'', '') new_version = str(str(str(requests.get('https://raw.githubusercontent.com/ElBe-Plaq/discord.py-bot-template/main/version.py').text).replace('version = ', '')).replace('\n', '')).replace('\'', '')
if version == new_version: if version == new_version:
try: try:
client.run(token, log_handler=None) client.run(token, log_handler=None)
except discord.errors.DiscordException: except discord.errors.DiscordException:
errors.APIError('Error while trying to connect to discord.') errors.APIError('Error while trying to connect to discord.')
else: else:
errors.OutdatedVersionError('the template', new_version, 'https://github.com/ElBe-Plaq/discord.py-bot-template') errors.OutdatedVersionError('the template', new_version, 'https://github.com/ElBe-Plaq/discord.py-bot-template')

View File

@ -2,17 +2,17 @@
Slash command creator for the discord.py Bot. Slash command creator for the discord.py Bot.
© by ElBe. © by ElBe.
Version: 0.1.5 Version: 1.4
''' '''
#Imports #Imports
import os
import requests import requests
import functions
#Variables #Variables
url = 'https://discord.com/api/v10/applications/' + str(os.environ['application_id']) + '/commands' url = 'https://discord.com/api/v10/applications/' + str(functions.json_module.get_config('Config')['Application ID']) + '/commands'
headers = { headers = {
'Authorization': 'Bot ' + str(os.environ['token']) 'Authorization': 'Bot ' + str(functions.json_module.get_config('Config')['Token'])
} }
#Example Command #Example Command
@ -26,6 +26,5 @@ json = {
def create_command(json): def create_command(json):
try: try:
r = requests.post(url, headers=headers, json=json) r = requests.post(url, headers=headers, json=json)
print('Command /' + str(json['name']) + ' was sucessfully created.')
except Exception as e: except Exception as e:
print('Error while trying to create the command /' + str(json['name']) + '.\n' + str(e)) print('Error while trying to create the command /' + str(json['name']) + '.\n' + str(e))

1
Bot/commands.json Normal file
View File

@ -0,0 +1 @@
{"Created": 0}

View File

@ -1,110 +1,110 @@
''' '''
Command creator for the discord.py Bot. Command creator for the discord.py Bot.
© by ElBe. © by ElBe.
Version: 0.1.5 Version: 1.5
NOTE: Only execute once. NOTE: Only execute once.
''' '''
#Imports #Imports
import command_creator import command_creator
#Stop command #Stop command
json = { json = {
'name': 'stop', 'name': 'stop',
'type': 1, 'type': 1,
'description': 'Stops the bot.' 'description': 'Stops the bot.'
} }
command_creator.create_command(json) command_creator.create_command(json)
#Help command #Help command
json = { json = {
'name': 'help', 'name': 'help',
'type': 1, 'type': 1,
'description': 'Shows you help about the bot.' 'description': 'Shows you help about the bot.'
} }
command_creator.create_command(json) command_creator.create_command(json)
#Ping command #Ping command
json = { json = {
'name': 'ping', 'name': 'ping',
'type': 1, 'type': 1,
'description': 'Shows you the ping of the bot in ms.' 'description': 'Shows you the ping of the bot in ms.'
} }
command_creator.create_command(json) command_creator.create_command(json)
#Info command #Info command
json = { json = {
'name': 'info', 'name': 'info',
'type': 1, 'type': 1,
'description': 'Shows you information about the bot.' 'description': 'Shows you information about the bot.'
} }
command_creator.create_command(json) command_creator.create_command(json)
#Kick command #Kick command
json = { json = {
'name': 'kick', 'name': 'kick',
'type': 1, 'type': 1,
'description': 'Kicks a member from the server.', 'description': 'Kicks a member from the server.',
"options": [ "options": [
{ {
"name": "member", "name": "member",
"description": "The member to kick.", "description": "The member to kick.",
"type": 6, "type": 6,
"required": True "required": True
}, },
{ {
"name": "reason", "name": "reason",
"description": "Reason for the kick.", "description": "Reason for the kick.",
"type": 3, "type": 3,
"required": False "required": False
} }
] ]
} }
command_creator.create_command(json) command_creator.create_command(json)
#Ban command #Ban command
json = { json = {
'name': 'ban', 'name': 'ban',
'type': 1, 'type': 1,
'description': 'Bans a member from the server.', 'description': 'Bans a member from the server.',
"options": [ "options": [
{ {
"name": "member", "name": "member",
"description": "The member to ban.", "description": "The member to ban.",
"type": 6, "type": 6,
"required": True "required": True
}, },
{ {
"name": "reason", "name": "reason",
"description": "Reason for the ban.", "description": "Reason for the ban.",
"type": 3, "type": 3,
"required": False "required": False
} }
] ]
} }
command_creator.create_command(json) command_creator.create_command(json)
#Unban command #Unban command
json = { json = {
'name': 'unban', 'name': 'unban',
'type': 1, 'type': 1,
'description': 'Unbans a member from the server.', 'description': 'Unbans a member from the server.',
"options": [ "options": [
{ {
"name": "member", "name": "member",
"description": "The member to unban.", "description": "The member to unban.",
"type": 6, "type": 6,
"required": True "required": True
}, },
{ {
"name": "reason", "name": "reason",
"description": "Reason for the unban.", "description": "Reason for the unban.",
"type": 3, "type": 3,
"required": False "required": False
} }
] ]
} }
command_creator.create_command(json) command_creator.create_command(json)

View File

@ -1,13 +1,18 @@
{ {
"Config": { "Config": {
"Version": "1.9.2 final-r", "Token": "<INSERT TOKEN HERE>",
"Version-Comment": "Bugfix and error handler.", "Application ID": "<INSERT APPLICATION ID HERE>",
"Footer": "Bot made by ElBe.", "Version": "1.9.3 final",
"Version-Comment": "Added error handling.",
"Footer": "Made by ElBe.",
"Credits": true "Credits": true
}, },
"Channels": { "Channels": {
"Welcome": "<Insert welcome channel name here>", "Welcome": "",
"Goodbye": "<Insert goodbye channel name here>" "Goodbye": ""
},
"Roles": {
"Member": "member"
}, },
"Commands": { "Commands": {
"stop": true, "stop": true,

24
Bot/errors.py Normal file
View File

@ -0,0 +1,24 @@
'''
Errors for the discord.py Bot.
© by ElBe.
Version: 1.0
'''
#Imports
import functions
#Error
class error():
def __init__(self, name: str, text: str):
functions.console.error(name + '\n' + text)
exit()
#API error
class APIError(error):
def __init__(self, text: str):
super().__init__('API error', text)
#OutdatedVersionError
class OutdatedVersionError():
def __init__(self, outdated: str, version: str, download: str):
functions.console.warn('Outdated version\nYou installed an outdated version of ' + outdated + '. Please install version ' + version + ' from ' + download + '.')

View File

@ -1,106 +1,118 @@
''' '''
Functions for the discord.py Bot. Functions for the discord.py Bot.
© by ElBe. © by ElBe.
Version: 0.1.1 Version: 1.2
''' '''
#Imports #Imports
import json import json
import os import os
import colorama import colorama
import datetime import datetime
import re import re
import requests
class variables():
'''All variables used in this module.''' #Bot modules
standart_config_file = 'config.json' import errors
standart_datetime_format = datetime.date.isoformat
class variables():
class json_module(): '''All variables used in this module.'''
def get_config(name: str, file = variables.standart_config_file): standart_config_file = 'config.json'
'''Returns a value from the given/standart JSON file.''' standart_datetime_format = datetime.date.isoformat
with open(file, 'r') as f:
return json.load(f)[name] class json_module():
def get_config(name: str, file = variables.standart_config_file):
def write_json(data, show_text = False, file = variables.standart_config_file): '''Returns a value from the given/standart JSON file.'''
'''Writes the text to the given/standart JSON file.''' with open(file, 'r') as f:
with open(file, 'w') as f: return json.load(f)[name]
json.dump(data, f)
f.close() def write_json(data, show_text = False, file = variables.standart_config_file):
'''Writes the text to the given/standart JSON file.'''
if show_text: with open(file, 'w') as f:
print(console.log('Data ' + str(data) + ' added to ' + str(file) + '.')) json.dump(data, f)
f.close()
class console():
def info(text: str): if show_text:
'''Returns a info text.''' print(console.log('Data ' + str(data) + ' added to ' + str(file) + '.'))
i = 0
if len(re.findall('\n', text)) > 1: class console():
text = '\n' + text def info(text: str):
search = len(re.findall('\n', text)) '''Returns a info text.'''
i = 0
if search > 1: if len(re.findall('\n', text)) > 1:
for i in range(search): text = '\n' + text
text = text.replace('\n', '//n[' + colorama.Fore.LIGHTBLUE_EX + str(i + 1) + colorama.Style.RESET_ALL + '] ', 1) search = len(re.findall('\n', text))
i = i + 1
text = text.replace('//n', '\n') if search > 1:
return colorama.Fore.LIGHTBLUE_EX + str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + colorama.Style.RESET_ALL + ' [' + colorama.Fore.GREEN + 'INFO' + colorama.Style.RESET_ALL + '] ' + text for i in range(search):
text = text.replace('\n', '//n[' + colorama.Fore.LIGHTBLUE_EX + str(i + 1) + colorama.Style.RESET_ALL + '] ', 1)
def error(text: str): i = i + 1
'''Returns a error text.''' text = text.replace('//n', '\n')
i = 0 return colorama.Fore.LIGHTBLUE_EX + str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + colorama.Style.RESET_ALL + ' [' + colorama.Fore.GREEN + 'INFO' + colorama.Style.RESET_ALL + '] ' + text
if len(re.findall('\n', text)) > 1:
text = '\n' + text def error(text: str):
search = len(re.findall('\n', text)) '''Returns a error text.'''
i = 0
if search > 1: if len(re.findall('\n', text)) > 1:
for i in range(search): text = '\n' + text
text = text.replace('\n', '//n[' + colorama.Fore.LIGHTBLUE_EX + str(i + 1) + colorama.Style.RESET_ALL + '] ', 1) search = len(re.findall('\n', text))
i = i + 1
text = text.replace('//n', '\n') if search > 1:
return colorama.Fore.LIGHTBLUE_EX + str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + colorama.Style.RESET_ALL + ' [' + colorama.Fore.RED + 'ERROR' + colorama.Style.RESET_ALL + '] ' + text for i in range(search):
text = text.replace('\n', '//n[' + colorama.Fore.LIGHTBLUE_EX + str(i + 1) + colorama.Style.RESET_ALL + '] ', 1)
def warn(text: str): i = i + 1
'''Returns a warn text.''' text = text.replace('//n', '\n')
i = 0 return colorama.Fore.LIGHTBLUE_EX + str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + colorama.Style.RESET_ALL + ' [' + colorama.Fore.RED + 'ERROR' + colorama.Style.RESET_ALL + '] ' + text
if len(re.findall('\n', text)) > 1:
text = '\n' + text def warn(text: str):
search = len(re.findall('\n', text)) '''Returns a warn text.'''
i = 0
if search > 1: if len(re.findall('\n', text)) > 1:
for i in range(search): text = '\n' + text
text = text.replace('\n', '//n[' + colorama.Fore.LIGHTBLUE_EX + str(i + 1) + colorama.Style.RESET_ALL + '] ', 1) search = len(re.findall('\n', text))
i = i + 1
text = text.replace('//n', '\n') if search > 1:
return colorama.Fore.LIGHTBLUE_EX + str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + colorama.Style.RESET_ALL + ' [' + colorama.Fore.YELLOW + 'WARNING' + colorama.Style.RESET_ALL + '] ' + text for i in range(search):
text = text.replace('\n', '//n[' + colorama.Fore.LIGHTBLUE_EX + str(i + 1) + colorama.Style.RESET_ALL + '] ', 1)
def log(text: str): i = i + 1
'''Returns a log text.''' text = text.replace('//n', '\n')
i = 0 return colorama.Fore.LIGHTBLUE_EX + str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + colorama.Style.RESET_ALL + ' [' + colorama.Fore.YELLOW + 'WARNING' + colorama.Style.RESET_ALL + '] ' + text
if len(re.findall('\n', text)) > 1:
text = '\n' + text def log(text: str):
search = len(re.findall('\n', text)) '''Returns a log text.'''
i = 0
if search > 1: if len(re.findall('\n', text)) > 1:
for i in range(search): text = '\n' + text
text = text.replace('\n', '//n[' + colorama.Fore.LIGHTBLUE_EX + str(i + 1) + colorama.Style.RESET_ALL + '] ', 1) search = len(re.findall('\n', text))
i = i + 1
text = text.replace('//n', '\n') if search > 1:
return colorama.Fore.LIGHTBLUE_EX + str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + colorama.Style.RESET_ALL + ' [LOG] ' + text for i in range(search):
text = text.replace('\n', '//n[' + colorama.Fore.LIGHTBLUE_EX + str(i + 1) + colorama.Style.RESET_ALL + '] ', 1)
def clear(): i = i + 1
'''Clear the console.''' text = text.replace('//n', '\n')
os.system('cls') return colorama.Fore.LIGHTBLUE_EX + str(datetime.datetime.now().strftime('%d.%m.%Y %T')) + colorama.Style.RESET_ALL + ' [LOG] ' + text
def crusor_up(): def clear():
'''Changes the position of the crusor to the line above.''' '''Clear the console.'''
print('\x1b[1A') os.system('cls')
def erase_line(): def crusor_up():
'''Erases the current line.''' '''Changes the position of the crusor to the line above.'''
print('\x1b[2K') print('\x1b[1A')
def erase_last(): def erase_line():
'''Erases the last line.''' '''Erases the current line.'''
print('\x1b[1A' + '\x1b[2K' + '\x1b[1A') print('\x1b[2K')
def erase_last():
'''Erases the last line.'''
print('\x1b[1A' + '\x1b[2K' + '\x1b[1A')
class outdated():
def __init__(package: str, min_version: str):
min_version_int = int(min_version.replace('.',''))
try:
latest_version = int(str(json.loads(requests.get('https://pypi.python.org/pypi/' + package + '/json').text)['info']['version']).replace('.', ''))
except Exception as e:
print(console.error('Package not found.'))

View File

@ -1 +1 @@
__version__ = '1.9.2' version = '1.9.3'