New logging

This commit is contained in:
Logan Cusano
2022-03-28 01:27:37 -04:00
parent d97e51d960
commit c741288b87
7 changed files with 158 additions and 95 deletions

88
bot.py
View File

@@ -1,4 +1,5 @@
import asyncio
import logging
import os
import platform
import discord
@@ -17,6 +18,9 @@ class Bot(commands.Bot):
commands.Bot.__init__(self, command_prefix=commands.when_mentioned_or(kwargs['command_prefix']),
activity=discord.Game(name=f"@ me"), status=discord.Status.idle)
# Create the logger for the bot
self.logger = logging.getLogger("Discord_Radio_Bot.Bot")
# Init the core bot variables
self.DEVICE_ID = kwargs['Device_ID']
self.DEVICE_NAME = kwargs['Device_Name']
@@ -82,7 +86,7 @@ class Bot(commands.Bot):
brief="Joins the voice channel that the caller is in")
async def join(ctx, *, member: discord.Member = None):
member = member or ctx.author.display_name
print(f"Join requested by {member}")
self.logger.info(f"Join requested by {member}")
if not self.Bot_Connected:
# Wait for the bot to be ready to connect
@@ -93,15 +97,15 @@ class Bot(commands.Bot):
if discord.opus.is_loaded():
channel = ctx.author.voice.channel
print("Sending hello")
self.logger.debug("Sending hello")
await ctx.send(f"Ok {str(member).capitalize()}, I'm joining {channel}")
# Join the voice channel with the audio stream
print('Joining')
self.logger.debug('Joining')
voice_connection = await channel.connect()
# Create an audio stream from selected device
print("Starting noisegate/stream handler")
self.logger.debug("Starting noisegate/stream handler")
self.streamHandler = NoiseGatev2.NoiseGate(_input_device_index=self.DEVICE_ID,
_voice_connection=voice_connection,
_noise_gate_threshold=self.noisegate_sensitivity)
@@ -109,61 +113,62 @@ class Bot(commands.Bot):
self.streamHandler.run()
# Start the SDR and begin playing to the audio stream
print("Starting SDR")
self.logger.debug("Starting SDR")
self.start_sdr()
# Change the activity to the channel and band-type being used
print("Changing presence")
self.logger.debug("Changing presence")
await self.set_activity()
# 'Lock' the bot from connecting
print("Locking the bot")
self.logger.debug("Locking the bot")
self.Bot_Connected = True
else:
# Return that the opus library would not load
await ctx.send("Opus won't load")
print("OPUS didn't load properly")
self.logger.critical("OPUS didn't load properly")
else:
await ctx.send(f"{str(member).capitalize()}, I'm already connected")
print("Bot is already in a channel")
self.logger.info("Bot is already in a channel")
@self.command(help="Use this command to have the bot leave your channel",
brief="Leaves the current voice channel")
async def leave(ctx, member: discord.Member = None):
member = member or ctx.author.display_name
print(f"Leave requested by {member}")
self.logger.info(f"Leave requested by {member}")
if self.Bot_Connected:
# Stop the sound handlers
# Disconnect the client from the voice channel
print("Disconnecting")
self.logger.debug("Disconnecting")
await self.streamHandler.close()
print("Changing presence")
self.logger.debug("Changing presence")
# Change the presence to away and '@ me'
await self.set_activity(False)
# Stop the SDR so it can cool off
print("Stopping SDR")
self.logger.debug("Stopping SDR")
self.stop_sdr()
print("Unlocking the bot")
self.logger.debug("Unlocking the bot")
# 'Unlock' the bot
self.Bot_Connected = False
print("Sending Goodbye")
self.logger.debug("Sending Goodbye")
await ctx.send(f"Goodbye {str(member).capitalize()}.")
else:
await ctx.send(f"{str(member).capitalize()}, I'm not in a channel")
self.logger.info("Bot is not in a channel")
# Add command to change the NoiseGate threshold
@self.command(help="Use this command to change the threshold of the noisegate",
brief="Change noisegate sensitivity")
async def chngth(ctx, _threshold: int, member: discord.Member = None):
member = member or ctx.author.display_name
print(f"Change of NoiseGate threshold requested by {member}")
self.logger.info(f"Change of NoiseGate threshold requested by {member}")
await ctx.send(f"Ok {str(member).capitalize()}, I'm changing the threshold from "
f"{self.streamHandler.THRESHOLD} to {_threshold}")
self.streamHandler.THRESHOLD = _threshold
@@ -182,6 +187,7 @@ class Bot(commands.Bot):
member = member or ctx.author.display_name
message = self.display_current_radio_config()
await ctx.send(f"Ok {str(member).capitalize()},\n{message}")
self.logger.info(f"Displaying current profile; requested by {member}")
# Command to display the current config
@self.command(name='displayprofiles',
@@ -193,6 +199,7 @@ class Bot(commands.Bot):
member = member or ctx.author.display_name
message = self.display_saved_radio_configs()
await ctx.send(f"Ok {str(member).capitalize()},\n{message}")
self.logger.info(f"Displaying all profiles; requested by {member}")
# Command to change the current frequency and mode
@self.command(name='chfreq', help="Use this command to change the frequency the bot is listening to.\n"
@@ -205,6 +212,7 @@ class Bot(commands.Bot):
async def chfreq(ctx, mode: str, freq: str, member: discord.Member = None):
# Possible band-types that can be used
member = member or ctx.author.display_name
self.logger.info(f"{member} requested change of frequency to Mode: {mode}, Freq: {freq}")
# Check to make sure the frequency input matches the syntax needed
if len(freq) >= 6:
@@ -240,6 +248,7 @@ class Bot(commands.Bot):
brief="Changes radio squelch")
async def chsquelch(ctx, squelch: float, member: discord.Member = None):
member = member or ctx.author.display_name
self.logger.info(f"{member} requested change of squelch to: {squelch}")
self.squelch = squelch
await ctx.send(f"Ok {str(member).capitalize()}, I'm changing the squelch to {self.squelch}")
@@ -289,13 +298,13 @@ class Bot(commands.Bot):
async def on_ready():
# Check the ./modules folder for any modules (cog.py)
await self.check_for_modules()
print("Bot started!")
self.logger.info("Bot started!")
# Check to see if other bots are online
async def check_other_bots_online(self):
print('Checking if other bots are online')
self.logger.info('Checking if other bots are online')
channel = self.get_channel(self.Default_Channel_ID)
print(f"Testing in: {channel}")
self.logger.debug(f"Testing in: {channel}")
bots_online = []
@@ -315,7 +324,7 @@ class Bot(commands.Bot):
except asyncio.exceptions.TimeoutError:
seconds_waited += 1
print(f"Bots Online: {bots_online}")
self.logger.debug(f"Bots Online: {bots_online}")
if len(bots_online) == 0:
return False
@@ -325,13 +334,13 @@ class Bot(commands.Bot):
# Check the handler being used during init
def check_handler(self):
if self.Handler == "gqrx":
print("Starting GQRX handler")
self.logger.info("Starting GQRX handler")
from gqrxHandler import GQRXHandler
self.GQRXHandler = GQRXHandler()
self.possible_modes = BotResources.PDB_ACCEPTABLE_HANDLERS['gqrx']['Modes']
elif self.Handler == 'op25':
print("Starting OP25 handler")
self.logger.info("Starting OP25 handler")
from op25Handler import OP25Handler
self.OP25Handler = OP25Handler()
self.OP25Handler.start()
@@ -342,22 +351,22 @@ class Bot(commands.Bot):
# Check the system type and load the correct library
# Linux ARM AARCH64 running 32bit OS
if self.system_os_type == 'Linux_ARMv7l':
print(f"Loaded OPUS library for {self.system_os_type}")
self.logger.debug(f"Loaded OPUS library for {self.system_os_type}")
discord.opus.load_opus('./opus/libopus_armv7l.so')
# Linux ARM AARCH64 running 64bit OS
if self.system_os_type == 'Linux_AARCH64':
print(f"Loaded OPUS library for {self.system_os_type}")
self.logger.debug(f"Loaded OPUS library for {self.system_os_type}")
discord.opus.load_opus('./opus/libopus_aarcch64.so')
# Windows 64bit
if self.system_os_type == 'Windows_x64':
print(f"Loaded OPUS library for {self.system_os_type}")
self.logger.debug(f"Loaded OPUS library for {self.system_os_type}")
discord.opus.load_opus('./opus/libopus_amd64.dll')
# Check to make sure the selected device is still available and has not changed its index
def check_device(self, _override):
# Check to see if an override has been passed
if not _override:
print(f"Device list {self.Devices_List}")
self.logger.debug(f"Device list {self.Devices_List}")
for device, index in self.Devices_List['Input']:
if int(index) == self.DEVICE_ID and str(device) == self.DEVICE_NAME:
return True
@@ -382,19 +391,19 @@ class Bot(commands.Bot):
if str(folder_name)[0] == '.':
continue
elif os.path.exists(os.path.join("modules", folder_name, "cog.py")):
print(f"Loaded extension: {folder_name}")
self.logger.debug(f"Loaded extension: {folder_name}")
self.load_extension(f"modules.{folder_name}.cog")
# Reload a selected module for changes
def reload_modules(self, module):
try:
self.unload_extension(f"modules.{module}.cog")
print(f"Unloaded {module}")
self.logger.debug(f"Unloaded {module}")
self.load_extension(f"modules.{module}.cog")
print(f"Loaded {module}")
self.logger.debug(f"Loaded {module}")
return True
except Exception as e:
print(e)
self.logger.error(e)
return False
# Check and store the OS type of the system for later use
@@ -403,14 +412,14 @@ class Bot(commands.Bot):
if os.name == 'nt':
if processor == "AMD64":
self.system_os_type = 'Windows_x64'
print(f"OS/Arch is {self.system_os_type}")
self.logger.debug(f"OS/Arch is {self.system_os_type}")
else:
if processor == "aarch64":
self.system_os_type = 'Linux_AARCH64'
print(f"OS/Arch is {self.system_os_type}")
self.logger.debug(f"OS/Arch is {self.system_os_type}")
elif processor == "armv7l":
self.system_os_type = 'Linux_ARMv7l'
print(f"OS/Arch is {self.system_os_type}")
self.logger.debug(f"OS/Arch is {self.system_os_type}")
# Check to see if there is only one frequency
def start_sdr(self):
@@ -421,7 +430,7 @@ class Bot(commands.Bot):
self.stop_sdr()
# Start the radio
print(f"Starting freq: {self.freq}")
self.logger.debug(f"Starting freq: {self.freq}")
if self.Handler == 'gqrx':
# Set the settings in GQRX
@@ -466,7 +475,7 @@ class Bot(commands.Bot):
# Save the current radio settings as a profile
async def save_radio_config(self, _profile_name: str):
print(f"Saving profile {_profile_name}")
self.logger.debug(f"Saving profile {_profile_name}")
config = configparser.SafeConfigParser()
if os.path.exists('./profiles.ini'):
@@ -493,7 +502,7 @@ class Bot(commands.Bot):
# Load a saved profile into the current settings
async def load_radio_config(self, profile_name):
print(f"Loading profile {profile_name}")
self.logger.debug(f"Loading profile {profile_name}")
config = configparser.ConfigParser()
if os.path.exists('./profiles.ini'):
config.read('./profiles.ini')
@@ -505,8 +514,9 @@ class Bot(commands.Bot):
try:
self.noisegate_sensitivity = int(config[self.profile_name]['Noisegate_Sensitivity'])
except KeyError:
print(f"Config does not contain a 'noisegate sensitivity' value, "
f"creating one now with the default value: {BotResources.DEFAULT_NOISEGATE_THRESHOLD}")
self.logger.warning(f"Config does not contain a 'noisegate sensitivity' value, "
f"creating one now with the default value: "
f"{BotResources.DEFAULT_NOISEGATE_THRESHOLD}")
self.noisegate_sensitivity = BotResources.DEFAULT_NOISEGATE_THRESHOLD
await self.save_radio_config(self.profile_name)
@@ -544,7 +554,7 @@ class Bot(commands.Bot):
try:
message_body += f"\tNoisegate Sensitivity:\t{config[section]['Noisegate_Sensitivity']}\n"
except KeyError:
print(f"Config does not contain a 'noisegate sensitivity' value. Please load the profile")
self.logger.warning(f"Config does not contain a 'noisegate sensitivity' value. Please load the profile")
message_body += f"\tSquelch:\t\t\t\t{config[section]['Squelch']}\n"