Files
Discord-Radio-Bot/bot.py

214 lines
9.0 KiB
Python

import os
import re
import time
import discord
import sound
from discord.ext import commands
from main import write_config_file
from subprocess import Popen, PIPE
class Bot(commands.Bot):
def __init__(self, **kwargs): # bot_token, device_id, device_name, command_prefix='>!'):
if 'command_prefix' not in kwargs.keys():
kwargs['command_prefix'] = '>!'
commands.Bot.__init__(self, command_prefix=commands.when_mentioned_or(kwargs['command_prefix']),
activity=discord.Game(name=f"@me"), status=discord.Status.idle)
self.DEVICE_ID = kwargs['Device_ID']
self.DEVICE_NAME = kwargs['Device_Name']
self.BOT_TOKEN = kwargs['Token']
self.Default_Channel_ID = kwargs['Channel_ID']
self.Default_Mention_Group = kwargs['Mention_Group']
self.Devices_List = sound.query_devices().items()
# Init radio parameters
self.freq = "104.7M"
self.freq_re = re.compile('(\d+\.?\d*M)')
self.mode = "wbfm"
self.gain = 40
self.squelch = 0
self.sample_rate = ""
self.sample_rate_re = re.compile('(\d+\.?\d*k)')
# Init SDR Variables
self.sdr_process = None
self.system_os_type = None
self.sdr_output_process = None
self.sdr_started = False
# Set linux or windows
self.check_os_type()
self.add_commands()
self.check_for_modules()
def start_bot(self):
self.run(self.BOT_TOKEN)
def add_commands(self):
@self.command(help="Use this to test if the bot is alive", brief="Sends a 'pong' in response")
async def ping(ctx):
await ctx.send('pong')
@self.command(help="Use this command to join the bot to your channel",
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
await self.wait_until_ready()
discord.opus.load_opus('./opus/libopus.so')
if discord.opus.is_loaded():
stream = sound.PCMStream()
channel = ctx.author.voice.channel
await ctx.send(f"Ok {member}, I'm joining {channel}")
stream.change_device(self.DEVICE_ID)
voice_connection = await channel.connect()
voice_connection.play(discord.PCMAudio(stream))
self.start_sdr()
await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening,
name="the airwaves"),
status=discord.Status.online)
else:
await ctx.send("Opus won't load")
@self.command(help="Use this command to have the bot leave your channel",
brief="Leaves the current voice channel")
async def leave(ctx):
await ctx.voice_client.disconnect()
await self.change_presence(activity=discord.Game(name=f"@me"), status=discord.Status.idle)
@self.command(name='chfreq', help="Use this command to change the frequency the bot is listening to. Note: 'M'"
"is required\nExmple command: '@ chfreq <['fm', 'wbfm']> <xxx.xxxM>",
brief="Changes radio frequency")
async def chfreq(ctx, mode: str, freq: str, member: discord.Member = None):
possible_modes = ['wbfm', 'fm']
member = member or ctx.author.display_name
if self.freq_re.search(freq):
self.freq = freq
if mode in possible_modes:
self.mode = mode
await ctx.send(f"Ok {member}, I have changed the mode to {self.mode} and frequency to {self.freq}")
if self.sdr_started:
self.start_sdr()
else:
await ctx.send(f"{member}, {mode} is not valid. You may only enter 'fm' or 'wbfm'")
else:
await ctx.send(f"{member}, {freq} is not valid. please refer to the help page '@ help chfreq'")
@self.command(name='chsquelch', help="Use this command to change the squelch for the frequency"
"the bot is listening to",
brief="Changes radio squelch")
async def chsquelch(ctx, squelch: int, member: discord.Member = None):
member = member or ctx.author.display_name
self.squelch = squelch
await ctx.send(f"Ok {member}, I have changed the squelch to {self.squelch}")
if self.sdr_started:
self.start_sdr()
@self.command(name='chgain', help="Use this command to change the radio gain for the bot",
brief="Changes radio gain")
async def chgain(ctx, gain: int, member: discord.Member = None):
member = member or ctx.author.display_name
self.gain = gain
await ctx.send(f"Ok {member}, I have changed the gain to {self.gain}")
if self.sdr_started:
self.start_sdr()
@self.command(name='chbw', help="Use this command to change the center frequency bandwidth for the bot."
"Note: 'k' is required\nExample Command: '@ chbw <xxx.xxk'",
brief="Changes radio bandwidth")
async def chbw(ctx, sample_rate: str, member: discord.Member = None):
member = member or ctx.author.display_name
if self.sample_rate_re.search(sample_rate):
self.sample_rate = sample_rate
await ctx.send(f"Ok {member}, I have changed the sample rate to {self.sample_rate}")
if self.sdr_started:
self.start_sdr()
else:
await ctx.send(f"{member}, {sample_rate} is not valid. please refer to the help page '@ help chbw'")
@self.command(name='reload', hidden=True)
async def _reload(ctx, module: str, member: discord.Member = None):
"""Reloads a module."""
member = member or ctx.author.display_name
if self.reload_modules(module):
await ctx.send(f"Ok {member}, I reloaded {module}")
else:
await ctx.send(f"{member}, something went wrong. Please check the console")
@self.command(name='startsdr', hidden=True)
async def _startsdr(ctx, input_freq: str, member: discord.Member = None):
member = member or ctx.author.display_name
self.start_sdr()
def check_device(self):
for device, index in self.Devices_List:
if int(index) == self.DEVICE_ID and str(device) == self.DEVICE_NAME:
return True
for device, index in self.Devices_List:
if str(device) == self.DEVICE_NAME:
self.DEVICE_ID = int(index)
return True
else:
return False
def check_for_modules(self):
for folder_name in os.listdir("modules"):
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.load_extension(f"modules.{folder_name}.cog")
def reload_modules(self, module):
try:
self.unload_extension(f"modules.{module}.cog")
print(f"Unloaded {module}")
self.load_extension(f"modules.{module}.cog")
print(f"Loaded {module}")
return True
except Exception as e:
print(e)
return False
def check_os_type(self):
if os.name == 'nt':
self.system_os_type = 'Windows'
else:
self.system_os_type = 'Linux'
def start_sdr(self):
if type(self.freq) == str:
# Single freq sent
# Wait for the running processes to close
if self.sdr_started:
while self.sdr_process.poll() is None and self.sdr_output_process.poll() is None:
self.sdr_process.terminate()
self.sdr_process.kill()
time.sleep(1)
self.sdr_output_process.terminate()
self.sdr_output_process.kill()
time.sleep(1)
self.sdr_started = False
# Start the radio
print(f"Starting freq: {self.freq}")
self.sdr_process = Popen(["rtl_fm", "-M", str(self.mode), "-f", str(self.freq), "-g", str(self.gain),
"-l", str(self.squelch), "-s", str(self.sample_rate)],
stdout=PIPE)
self.sdr_output_process = Popen(["play", "-t", "raw", "-r", "32k", "-es", "-b", "16", "-c", "1", "-V1", "-"],
stdin=self.sdr_process.stdout)
self.sdr_started = True