Files
Discord-Radio-Bot/main.py
Logan Cusano 9334f51e22 Create GUI
Update README
2021-12-12 20:13:08 -05:00

336 lines
12 KiB
Python

import sys
import os
import threading
import time
import bot
import asyncio
from os.path import exists
from BotResources import check_if_config_exists, write_config_file, read_config_file, get_device_list
from PyQt6 import QtWidgets, QtGui
from PyQt6.QtCore import QObject, pyqtSignal, QThread
from PyQt6.QtWidgets import QMainWindow, QApplication
# Jorn
#token = 'OTE1MDY0OTk2OTk0NjMzNzI5.YaWKsA.Y9yaCGg_VXRL_qQVbs05vo7gSAc'
# Greada
#token = 'NzU2MzI3MjcxNTk3NDczODYz.X2QOqQ.LVLj2b-RXQzPmhNuBC1eGFMcYls'
#name = "VoiceMeeter Output"
class CreateConfigFile():
def __init__(self, **kwargs):
write_config_file(**kwargs)
class BotWorker(threading.Thread):
def __init__(self, config):
super(BotWorker, self).__init__()
self.config = config
self.discord_bot_client = bot.Bot(Token=self.config['Token'], Device_ID=self.config['Device ID'],
Device_Name=self.config['Device Name'],
Mention_Group=self.config['Mention Group'], Channel_ID=self.config['Channel ID'])
print(f"Verifying audio device:\t{self.config['Device Name']}")
if not self.discord_bot_client.check_device():
raise BotDeviceNotFound(self.config['Device Name'])
def run(self):
print("Bot started!")
self.discord_bot_client.start_bot()
async def stop_bot(self):
print("Stopping Bot")
await self.discord_bot_client.stop_bot()
print("ASD")
class mainWindow(QMainWindow):
def __init__(self):
super(mainWindow, self).__init__()
print('Checking config file...')
if check_if_config_exists():
self.config = read_config_file()
else:
self.config = None
windowDimensions, uiInformation = self.createInitVars()
self.windowDimensions = windowDimensions
self.uiInformation = uiInformation
self.device_list = get_device_list()
self.bot_thread = None
### UI Init
self.labelDevice = QtWidgets.QLabel(self)
self.contextEditMenu = QtWidgets.QMenu("&Edit", self)
self.contextFileMenu = QtWidgets.QMenu("&File", self)
self.btn1 = QtWidgets.QPushButton(self)
self.btn2 = QtWidgets.QPushButton(self)
self.btn3 = QtWidgets.QPushButton(self)
self.labelTitle = QtWidgets.QLabel(self)
self.labelToken = QtWidgets.QLabel(self)
self.labelMention_Group = QtWidgets.QLabel(self)
self.labelChannel_ID = QtWidgets.QLabel(self)
self.lineToken = QtWidgets.QLineEdit(self)
self.lineMention_Group = QtWidgets.QLineEdit(self)
self.lineChannel_ID = QtWidgets.QLineEdit(self)
self.comboDevice = QtWidgets.QComboBox(self)
self.contextMenuBar = self.menuBar()
self.createUI()
def createUI(self):
# Load Icon if one exists
if exists('./icon.png'):
self.setWindowIcon(QtGui.QIcon('./icon.png'))
# Loading text and UI variables
buttons = self.uiInformation['buttons']
labels = self.uiInformation['labels']
# Button 1 - Connect Bot
self.btn1.setText(buttons['btn1']['Text'])
self.btn1.clicked.connect(self.btn1Clicked)
self.btn1.move(self.windowDimensions['Width'] - 220, self.windowDimensions['Height'] - 40)
# Button 2 - Disconnect Bot
self.btn2.setText(buttons['btn2']['Text'])
self.btn2.setEnabled(False)
self.btn2.clicked.connect(self.btn2Clicked)
self.btn2.move(self.windowDimensions['Width'] - 110, self.windowDimensions['Height'] - 40)
# Button 3 - Save Config
self.btn3.setText(buttons['btn3']['Text'])
self.btn3.clicked.connect(self.btn3Clicked)
self.btn3.move(15, self.windowDimensions['Height'] - 40)
### Label Init
# Title
self.labelTitle.setText(labels['lblTitle']['Text'])
self.labelTitle.move(15, 30)
self.labelTitle.adjustSize()
# Token
self.labelToken.setText(labels['lblToken']['Text'])
self.labelToken.move(15, 70)
# Device
self.labelDevice.setText(labels['lblDevice']['Text'])
self.labelDevice.move(15, 190)
# Mention Group
self.labelMention_Group.setText(str(labels['lblMention_Group']['Text']))
self.labelMention_Group.move(15, 150)
self.labelMention_Group.adjustSize()
# Channel ID
self.labelChannel_ID.setText(str(labels['lblChannel_ID']['Text']))
self.labelChannel_ID.move(15, 110)
self.labelChannel_ID.adjustSize()
### Line Edit Init
# Token
self.lineToken.move(150, 75)
self.lineToken.resize(420, 28)
if self.config:
if 'Token' in self.config.keys():
self.lineToken.setText(self.config['Token'])
# Channel ID
self.lineChannel_ID.move(150, 115)
self.lineChannel_ID.resize(420, 28)
if self.config:
if 'Channel ID' in self.config.keys():
self.lineChannel_ID.setText(str(self.config['Channel ID']))
# Mention Group
self.lineMention_Group.move(150, 155)
self.lineMention_Group.resize(420, 28)
if self.config:
if 'Mention Group' in self.config.keys():
self.lineMention_Group.setText(self.config['Mention Group'])
# Device
for device, dev_id in self.device_list:
self.comboDevice.addItem(device)
self.comboDevice.move(150, 195)
self.comboDevice.resize(420, 28)
if self.config:
if 'Device Name' in self.config.keys():
self.comboDevice.setCurrentText(self.config['Device Name'])
### Window Setup
self.setGeometry(self.windowDimensions['Xpos'], self.windowDimensions['Ypos'], self.windowDimensions['Width'],
self.windowDimensions['Height'])
self.setFixedSize(self.windowDimensions['Width'], self.windowDimensions['Height'])
self.setWindowTitle(self.uiInformation['Title'])
# Creating file menu
self.contextMenuBar.addMenu(self.contextFileMenu)
# Creating edit menu
self.contextMenuBar.addMenu(self.contextEditMenu)
self.show()
def btn1Clicked(self):
if not self.config:
if len(self.lineToken.text()) == 59 and self.comboDevice.currentText() and len(
str(self.lineChannel_ID.text())) == len(
str("918029426397184000")) and self.lineMention_Group.text():
self.update_config()
CreateConfigFile(token=str(self.lineToken.text()), device_name=self.config['Device Name'],
device_id=self.config['Device ID'], channel_id=self.lineChannel_ID.text(),
mention_group=self.lineMention_Group.text())
self.config = read_config_file()
try:
clearance = 0
if self.update_config():
clearance += 1
if len(self.lineToken.text()) == 59:
clearance += 2
if clearance == 3:
self.bot_thread = BotWorker(self.config)
self.bot_thread.daemon = True
self.bot_thread.start()
elif clearance < 3:
raise Exception("Error in ID or Device")
except Exception as e:
print(e)
def btn2Clicked(self):
try:
asyncio.run(self.bot_thread.stop_bot())
self.bot_thread = BotWorker(self.config)
except Exception as e:
print(e)
return
def btn3Clicked(self):
print(len(self.lineToken.text()))
print(len(str(self.lineChannel_ID.text())))
print(self.comboDevice.currentText())
if len(self.lineToken.text()) == 59 and self.comboDevice.currentText() and len(
str(self.lineChannel_ID.text())) == len(
str("918029426397184000")) and self.lineMention_Group.text():
print('saving.....')
self.update_config()
CreateConfigFile(token=str(self.lineToken.text()), device_name=self.config['Device Name'],
device_id=self.config['Device ID'], channel_id=self.lineChannel_ID.text(), mention_group=self.lineMention_Group.text())
self.config = read_config_file()
print("Saved config")
return
def update_config(self):
if not self.config:
self.config = {}
for device, device_id in get_device_list():
if device == self.comboDevice.currentText():
self.config['Device ID'] = device_id
self.config['Device Name'] = device
return True
return False
def createInitVars(self):
windowDimensions = \
{
'Xpos': 400,
'Ypos': 300,
'Width': 600,
'Height': 325
}
uiInformation = \
{
'Title': "Simple Step Time Tracking",
'buttons':
{
'btn1':
{
'Text': "Connect Bot"
},
'btn2':
{
'Text': "Disconnect Bot"
},
'btn3':
{
'Text': "Save Config"
}
},
'labels':
{
'lblTitle':
{
'Text': "Please enter the fields below and click Connect!"
},
'lblToken':
{
'Text': "Bot Token:"
},
'lblChannel_ID':
{
'Text': "Default Text Channel ID:"
},
'lblMention_Group':
{
'Text': "Default Mention Group:"
},
'lblDevice':
{
'Text': "Input Device:"
},
'lblActivity':
{
'Text': "Activitiy"
},
'lblDescription':
{
'Text': "Description"
}
}
}
return windowDimensions, uiInformation
class BotDeviceNotFound(Exception):
def __init__(self, device):
print(f"Unable to find the device: {device}")
try:
os.remove('./config.ini')
except OSError:
print("Config file not found, restarting.")
#os.execv(__file__, sys.argv)
def main():
print('Starting Bot...')
try:
app = QApplication(sys.argv)
window = mainWindow()
sys.exit(app.exec())
except Exception as e:
print(e)
if __name__ == '__main__':
try:
print('Starting...')
while True:
try:
main()
except (BotDeviceNotFound, Exception) as e:
print(e)
print("Restarting...")
time.sleep(2)
except (KeyboardInterrupt, Exception) as e:
print(e)
print("Exiting...")