- Updates to bot responses

- Added BotResources.py
- Updates to saving and loading of config file
  - Updated how you call the save config function
  - Allowed saving of one variable
This commit is contained in:
Logan Cusano
2021-12-10 02:30:07 -05:00
parent 50c75aab2e
commit 72ccb1f737
5 changed files with 173 additions and 119 deletions

131
BotResources.py Normal file
View File

@@ -0,0 +1,131 @@
import sound
import configparser
from os.path import exists
def check_if_config_exists():
if exists('./config.ini'):
return True
else:
return False
def read_config_file():
config = configparser.ConfigParser()
config.read('./config.ini')
config_return = {
'Bot Token': config['Bot_Info']['Token'],
'Device ID': int(config['Device']['ID']),
'Device Name': str(config['Device']['Name']),
'Mention Group': str(config['Bot_Info']['Mention_Group']),
'Channel ID': int(config['Bot_Info']['Channel_ID'])
}
return config_return
def write_config_file(**kwargs):
config = configparser.SafeConfigParser()
if not kwargs['init'] and exists('./config.ini'):
config.read('./config.ini')
if not config.has_section('Bot_Info'):
config.add_section('Bot_Info')
if not config.has_section('Device'):
config.add_section('Device')
if kwargs['token']:
config['Bot_Info']['Token'] = kwargs['token']
elif kwargs['init']:
config['Bot_Info']['Token'] = get_user_token()
if kwargs['device_id'] or kwargs['device_name']:
config['Device']['ID'] = kwargs['device_id']
config['Device']['Name'] = kwargs['device_name']
elif kwargs['init']:
config['Device']['ID'], config['Device']['Name'] = get_user_device_selection()
if kwargs['mention_group']:
config['Bot_Info']['Mention_Group'] = kwargs['mention_group']
elif kwargs['init']:
config['Bot_Info']['Mention_Group'] = get_user_mention_group()
if kwargs['channel_id']:
config['Bot_Info']['Channel_ID'] = kwargs['channel_id']
elif kwargs['init']:
config['Bot_Info']['Channel_ID'] = str(get_user_mention_channel_id())
with open('./config.ini', 'w') as config_file:
config.write(config_file)
return True
def get_device_list():
return sound.query_devices().items()
def get_user_device_selection():
device_list = get_device_list()
org_device_list = []
for device, dev_id in device_list:
print(f"{dev_id + 1}\t-\t{device}")
org_device_list.append((dev_id, device))
selected_id = None
while not selected_id:
try:
selected_id = int(input(f"Please select the input device from above:\t")) - 1
except Exception as e:
print(e)
continue
if selected_id and not selected_id + 1 > int(len(device_list)):
continue
elif selected_id > int(len(device_list)):
print("Out of range, try again...")
selected_id = None
continue
else:
selected_id = None
print("Internal error, try again")
continue
for dev_dict in org_device_list:
if dev_dict[0] == selected_id:
selected_id = dev_dict
return selected_id
def get_user_token():
token = None
while not token:
token = str(input(f"Please enter your Discord bot API token now:\t"))
if len(token) == 59:
return token
else:
print('Length error in token, please try again...')
token = None
continue
def get_user_mention_group():
mention_group = None
while not mention_group:
mention_group = str(input(f"Please enter the name of the group you would like to mention:\t"))
return mention_group
def get_user_mention_channel_id():
channel_id = None
while not channel_id:
channel_id = int(input(f"Please enter the channel ID of the the default channel you would like messages to be sent in"))
if len(str(channel_id)) == len('757379843792044102'):
return channel_id
else:
print("Length error in ID, please try again")
channel_id = None
continue

View File

@@ -17,6 +17,10 @@ It will re-do the setup and allow you to select a new device.
### To-Do
- [x] Move cogs to their own files
- [ ] Add a disable function for cogs
- [X] Update WillieTimer with replies to all msgs
- [X] Add saving of changes to mention and channel
- [ ] Add a pool of responses to 4:20
- [ ] Send a message details of digital comms
- [ ] Send only one message at join and update this message with details of digital comms
- [ ] Interact with soapysdr directly from the bot

19
bot.py
View File

@@ -1,16 +1,20 @@
import os
import discord
import sound
from discord.ext import commands
from main import write_config_file
class Bot(commands.Bot):
def __init__(self, bot_token, device_id, device_name, command_prefix='>!'):
commands.Bot.__init__(self, command_prefix=commands.when_mentioned_or(command_prefix))
self.DEVICE_ID = int(device_id)
self.DEVICE_NAME = str(device_name)
self.BOT_TOKEN = str(bot_token)
def __init__(self, **kwargs): # bot_token, device_id, device_name, command_prefix='>!'):
if not kwargs['command_prefix']:
kwargs['command_prefix'] = '>!'
commands.Bot.__init__(self, command_prefix=commands.when_mentioned_or(kwargs['command_prefix']))
self.DEVICE_ID = int(kwargs['Device_ID'])
self.DEVICE_NAME = str(kwargs['Device_Name'])
self.BOT_TOKEN = str(kwargs['Token'])
self.Default_Channel_ID = int(kwargs['Channel_ID'])
self.Default_Mention_Group = str(kwargs['Mention_Group'])
self.Devices_List = sound.query_devices().items()
self.add_commands()
@@ -18,7 +22,6 @@ class Bot(commands.Bot):
self.check_for_modules()
def start_bot(self):
#self.add_cog(WillieTimer(self))
self.run(self.BOT_TOKEN)
def add_commands(self):
@@ -66,4 +69,4 @@ class Bot(commands.Bot):
for folder_name in os.listdir("modules"):
if os.path.exists(os.path.join("modules", folder_name, "cog.py")):
print(f"Loaded extension: {folder_name}")
self.load_extension(f"modules.{folder_name}.cog")
self.load_extension(f"modules.{folder_name}.cog")

102
main.py
View File

@@ -1,9 +1,7 @@
import configparser
import os
import time
import bot
import sound
from os.path import exists
from BotResources import check_if_config_exists, write_config_file, read_config_file
# Jorn
#token = 'OTE1MDY0OTk2OTk0NjMzNzI5.YaWKsA.Y9yaCGg_VXRL_qQVbs05vo7gSAc'
@@ -24,110 +22,18 @@ class BotDeviceNotFound(Exception):
#os.execv(__file__, sys.argv)
def check_if_config_exists():
if exists('./config.ini'):
return True
else:
return False
def read_config_file():
config = configparser.ConfigParser()
config.read('./config.ini')
config_return = {
'Bot Token': config['Bot_Info']['Token'],
'Device ID': int(config['Device']['ID']),
'Device Name': str(config['Device']['Name'])
}
return config_return
def write_config_file(token='', device_id=0, device_name=''):
config = configparser.ConfigParser()
config.add_section('Bot_Info')
config.add_section('Device')
if token == '' and device_id == 0:
device_id, device_name = get_user_device_selection()
print(device_id)
print(device_name)
token = get_user_token()
config['Bot_Info']['Token'] = token
config['Device']['ID'] = str(device_id)
config['Device']['Name'] = str(device_name)
with open('./config.ini', 'w') as config_file:
config.write(config_file)
return True
def get_device_list():
return sound.query_devices().items()
def get_user_device_selection():
device_list = get_device_list()
org_device_list = []
for device, dev_id in device_list:
print(f"{dev_id + 1}\t-\t{device}")
org_device_list.append((dev_id, device))
selected_id = None
while not selected_id:
try:
selected_id = int(input(f"Please select the input device from above:\t")) - 1
except Exception as e:
print(e)
continue
if selected_id and not selected_id + 1 > int(len(device_list)):
continue
elif selected_id > int(len(device_list)):
print("Out of range, try again...")
selected_id = None
continue
else:
selected_id = None
print("Internal error, try again")
continue
for dev_dict in org_device_list:
if dev_dict[0] == selected_id:
selected_id = dev_dict
return selected_id
def get_user_token():
token = None
while not token:
token = str(input(f"Please enter your Discord bot API token now:\t"))
if len(token) == 59:
return token
else:
print('Length error in token, please try again...')
continue
def main():
print('Checking config file...')
if not check_if_config_exists():
print("No config file exists, please enter this information now")
write_config_file()
write_config_file(init=True)
config = read_config_file()
print('Starting Bot...')
discord_bot_client = bot.Bot(config['Bot Token'], config['Device ID'], config['Device Name'])
discord_bot_client = bot.Bot(config['Bot Token'], config['Device ID'], config['Device Name'],
config['Mention Group'], config['Channel ID'])
print(f"Verifying audio device:\t{config['Device Name']}")

View File

@@ -3,13 +3,14 @@ import datetime
import discord
from discord.ext import commands
from discord.ext.tasks import loop
from BotResources import write_config_file
class WillieTimer(commands.Cog):
def __init__(self, bot, mention_group='Superadmins', channel_id=757379843792044102):
def __init__(self, bot): #, mention_group='Superadmins', channel_id=757379843792044102):
self.bot = bot
self.mention_group = str(mention_group)
self.channel_id = int(channel_id)
self.mention_group = str(self.bot.Default_Mention_Group)
self.channel_id = int(self.bot.Default_Channel_ID)
@loop(minutes=1)
async def bg_timer(self):
@@ -20,11 +21,7 @@ class WillieTimer(commands.Cog):
if datetime.datetime.now().strftime('%H:%M') in ("04:20", "16:20"):
print(f"It's {datetime.datetime.now().strftime('%H:%M:%S')}!")
channel = self.bot.get_channel(id=self.channel_id)
guild = channel.guild
role_id = discord.utils.get(guild.roles, name=self.mention_group)
print(role_id)
print(role_id.id)
await channel.send(f"<@&{role_id.id}> It's 4:20! It's time to light up!")
await channel.send(f"<@&{self.bot_get_role().id}> It's 4:20! It's time to light up!")
@commands.command(help="Use this command to start the background task to wait for 4:20",
brief="Starts the 4:20 clock")
@@ -47,8 +44,12 @@ class WillieTimer(commands.Cog):
message = int(message)
if message and len(str(message)) == len(str(self.channel_id)):
self.channel_id = message
print(message)
except:
await ctx.send(f"Ok {member}, I'll let Willie know to reach you in "
f"{self.bot.get_channel(id=self.channel_id)}")
print(message)
write_config_file(Channel_ID=self.channel_id)
except Exception as e:
print(f"Exception in chchn:\t{e}")
await ctx.send(f"{member}, {message} is not a valid channel ID, please try again")
pass
@@ -58,13 +59,22 @@ class WillieTimer(commands.Cog):
member = member or ctx.author.display_name
try:
message = str(message)
if message and len(str(message)) == len(str(self.channel_id)):
if message:
self.mention_group = message
print(message)
except:
await ctx.send(f"Ok {member}, I'll let Willie know to tell {self.bot_get_role()}")
print(message)
write_config_file(mention_group=self)
except Exception as e:
print(f"Exception in chmtn:\t{e}")
await ctx.send(f"{member}, {message} is not a valid role, please try again")
pass
def bot_get_role(self):
channel = self.bot.get_channel(id=self.channel_id)
guild = channel.guild
role = discord.utils.get(guild.roles, name=self.mention_group)
return role
def setup(bot: commands.Bot):
bot.add_cog(WillieTimer(bot))