initial commit

This commit is contained in:
iRaven 2024-10-26 04:47:45 -05:00
commit 9d837a1dad
16 changed files with 1022 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
__pycache__
settings.json
*.env
.idea
*.log
data/

15
cogs/embedtest.py Normal file
View File

@ -0,0 +1,15 @@
import json
import discord
from discord.ext import commands
## Xeno Discord PY Bot
### Embed Test
class EmbedTest(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def setup(bot):
print(f'Cog_EmbedTest is disabled, and will not be loaded.')
# await bot.add_cog(EmbedTest(bot))

21
cogs/example.txt Normal file
View File

@ -0,0 +1,21 @@
import json
import discord
from discord.ext import commands
## Xeno Discord PY Bot
### Command Name - Example
extname = (f'CommandName')
class CommandName(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='command',description='this is an example and shouldn\'t be run!')
async def idlookup(self, ctx):
await ctx.reply("This example command was run, and this reply will be sent to the channel it was ran in")
def setup(bot):
print(f'Cog_{extname} was initialized')
bot.add_cog(CommandName(bot))

106
cogs/fun.py Normal file
View File

@ -0,0 +1,106 @@
import json
import discord
import time
import requests
from discord.ext import commands
## Xeno Discord PY Bot
### Stupid fun commands
if __name__ == "__main__":
print("This is a cog (addon) for the Xeno Discord bot. This file cannot be run standalone.")
exit()
class FunCmds(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='ass', pass_context=True)
async def ass(self, ctx):
await ctx.send(f'It\'s time to chew ass and kick gum.')
time.sleep(1)
await ctx.send(f'And I\'m all out of ass.')
@commands.command(name='boob', pass_context=True)
async def boob(self, ctx):
await ctx.send(f'boob transformed is poop and it doesn\'t come out of it')
@commands.command(name='i!')
async def prefix1(self, ctx):
await ctx.send(f'That\'s more than expected...')
@commands.command(name='i!i!')
async def prefix2(self, ctx):
await ctx.send(f'wot you want bruh')
@commands.command(name='i!i!i!')
async def prefix3(self, ctx):
await ctx.send(f'Yeeeeeeeeeeeees?')
@commands.command(name='i!i!i!i!')
async def prefix4(self, ctx):
await ctx.send(f'Partner that\'s a bit too much, you\'re goin to the Principal\'s Office:tm:.')
@commands.command(name='longping')
async def longping(self, ctx):
await ctx.send(f'This is the first message, if you see another after 5 seconds Bozos isn\'t being an asshole and the bot is working')
time.sleep(5)
await ctx.send(f'If you see this message, 5 seconds have passed')
@commands.command(name='pigeon')
async def pigeon(self, ctx):
await ctx.send(f'I HAV ESCAPED FROM TEH POLICE')
time.sleep(0.5)
await ctx.send(f'THIS IS MY NEW HOME')
time.sleep(0.5)
await ctx.send(f'WITH DA PIGEON')
time.sleep(0.5)
await ctx.send(f'HELO PIGEON')
time.sleep(0.5)
await ctx.send(f'EHH')
time.sleep(0.2)
await ctx.send(f'EHH')
time.sleep(0.2)
await ctx.send(f'EHH')
@commands.command(name='starwars')
async def starwars(self, ctx):
await ctx.send(f'**DUUUUUUUUUUUUUUUUN**')
time.sleep(0.2)
await ctx.send(f'DUN DUN *DUUUUUUUUUUUUUN*')
await ctx.send(f'DUNDUNDUDNDUNDUDNUDNDNUDNDUNU**DNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN**')
time.sleep(0.2)
await ctx.send(f'DUN DUN DUN **DUUUUUUUUUUUUUUUUUUUUUUUUN** DUN DUND UDNDUNDUN*DNNNNNNNNNNNNNNNNNNNN*')
time.sleep(0.2)
await ctx.send(f'DUN DUND UDNDUNDUN*DNNNNNNNNNNNNNNNNNNNN*')
time.sleep(0.2)
await ctx.send(f'DUN DUND UDNDUNDUN**DNNNNNNNNNNNNNNNNNNNN**')
time.sleep(0.4)
await ctx.send(f'BOM BOM BOM *BAUUUUMMMM*')
await ctx.send(f'ok das it lmao hahah mr sunglasses ok no yas')
@commands.command(name='urban')
async def urban(self, ctx, arg):
urbanrq = requests.get(f'http://api.urbandictionary.com/v0/define?term={arg}')
# urbanjson = urbanrq.json() if urbanrq.status_code == 200 else None
urbanjson = None
if urbanrq.status_code == 200:
urbanjson = json.loads(urbanrq.text)
if (urbanjson.get('list') is not None):
# we may have found shit. keep going deeper.
if (urbanjson['list'].get('0') is not None):
# we found shit!
word = urbanjson['list']['0']['word']
def0 = urbanjson['list']['0']['definition']
exam0 = urbanjson['list']['0']['example']
embed=discord.Embed(title=word)
embed.add_field(name='Definition',value=def0,inline=False)
embed.add_field(name='Example',value=exam0,inline=False)
#embed.set_thumbnail(url=lkupuser.avatar)
await ctx.send(embed=embed)
else:
await ctx.reply("That word was not found.")
async def setup(bot):
print(f'Cog_FunCmds was initialized')
await bot.add_cog(FunCmds(bot))

42
cogs/mod.py Normal file
View File

@ -0,0 +1,42 @@
import json
import discord
from discord.ext import commands
from discord.errors import HTTPException, NotFound
## Xeno Discord PY Bot
### Moderation shit
extname = (f'Moderation')
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='idlookup',description='looks up user info by ID')
async def idlookup(self, ctx, arg):
# await ctx.reply(f'{arg} test')
intarg = int(arg)
try:
lkupuser = await self.bot.fetch_user(intarg) # for some reason this doesnt work and i have no idea why
#await ctx.reply(f'{lkupuser} test')
except NotFound:
print(f'Cog_{extname}: idlookup for ID {arg} returned a 404')
await ctx.reply(f'A user with the ID {arg} was not found.')
except HTTPException:
print(f'Cog_{extname}: idlookup for ID {arg} returned an HTTP Exception')
await ctx.reply(f'A lookup for a user with the ID {arg} failed.')
else:
# print(f'Cog_{extname}: idlookup for ID {arg} ({self.lkupuser}) succeeded')
embed=discord.Embed(title="User ID Lookup")
if lkupuser.discriminator is "0":
embed.add_field(name='Username:', value=f'{lkupuser.name}',inline=True)
else:
embed.add_field(name='Tag:',value=f'{lkupuser.name}#{lkupuser.discriminator}',inline=True)
embed.add_field(name='Is bot/system?',value=f'{lkupuser.bot} {lkupuser.system}',inline=True)
embed.add_field(name='Creation date:',value=f'{lkupuser.created_at}',inline=True)
embed.set_thumbnail(url=lkupuser.avatar)
# embed.set_footer(f'Requestor: {ctx.message.author.name},',f'{ctx.message.author.avatar}') # idk about this yet (hash on avatar?)
await ctx.send(embed=embed)
async def setup(bot):
print(f'Cog_{extname} was initialized')
await bot.add_cog(Moderation(bot))

133
cogs/radar.py Normal file
View File

@ -0,0 +1,133 @@
import json
from tracemalloc import stop
import discord
import wget
import requests
import random
import time
import os
from discord.ext import commands
## Xeno Discord PY Bot
### Radar Cog and Functionality
extname = (f'Radar')
randomnum = random.random()
# init local vars
initcurtime = time.localtime()
curtime = (f'{initcurtime.tm_hour}{initcurtime.tm_min}{initcurtime.tm_sec}')
curdate = (f'{initcurtime.tm_year}{initcurtime.tm_mon}{initcurtime.tm_mday}')
#make a cog.
class Radar(commands.Cog):
def __init__(self, bot):
self.bot = bot
#radar command define
@commands.command(name='radar', pass_context=True)
async def radarget(self, ctx, arg1):
fnameformat = (f'XenoRadar_{arg1}_{curdate}_{curtime}.gif')
imgname = fnameformat
print (f'Cog_Radar: The radar command was run! {curdate}@{curtime}')
#uparg1 = arg1.upper()
#uparg2 = arg2.upper()
if arg1 == "help":
await ctx.channel.send(f'With no special arguments, this help page will appear.\n Using the radar command fetches radar loops from NWS servers, 3 letters automatically adds *K* in front, such as *KHGX*. \nIf a radar site with 4 or more letters is specified, Xeno will automatically fetch a radar image for your input. \nUsing the **natl** argument gets a moasic of all radars in the major US.')
elif arg1 == "natl":
conusarg = ('CONUS-LARGE')
await self.newdownloadImage(conusarg, imgname)
# await self.downloadImage(f'conus')
#if arg1 and len(arg1) == 3:
# addkarg1 = ('K'+arg1)
# downloadImage(addkarg1)
else:
await self.newdownloadImage(arg1, imgname)
#argCheck(uparg1, uparg2)
if os.path.isfile(f'data/radar/{imgname}'):
print(f'\nCog_Radar: file {imgname} was downloaded!! now sending to channel') # (TODO: make this go in bot log and show actual stuff)
await ctx.reply(file=discord.File(f'data/radar/{imgname}'))
await ctx.send(f'current radar image for {arg1} as of {curtime} on {curdate}')
else:
print("Cog_Radar: error has occurred")
# print(f'{self.filepath}')
# print("bullshit!") # yes
# await ctx.send(file=discord.File(f'{self.radarupload()}'))
# let's fix this bitch
async def newdownloadImage(self, radarname, fileout):
tmpradarname = radarname
if radarname and len(radarname) == 3:
tmpradarname = (f'K{radarname}')
downloadradar = tmpradarname.upper()
# print ("shit!") # testing lmfao
# wget.download(f'https://radar.weather.gov/ridge/lite/{downloadradar}_loop.gif?{random.random()}',f'data/radar/{fileout}') # RIP /lite directory because NWS suddenly changed that? 11.21.22
# wget.download(f'https://radar.weather.gov/ridge/standard/{downloadradar}_loop.gif?{random.random()}',f'data/radar/{fileout}') # new /standard directory, not sure what changed
# copied the below method from TranstarArchive, it may be faster who fucking knows
rq = requests.get(f'https://radar.weather.gov/ridge/standard/{downloadradar}_loop.gif?{random.random()}')
open(f'data/radar/{fileout}', 'wb').write(rq.content)
# fin
# # downloads image based off of arguments from command
# async def downloadImage(self, radarname):
# loopname = radarname.upper()
# fnameformat = (f'XenoRadar_{radarname}_{curdate}_{curtime}.gif')
# imgname = fnameformat
# if 'conus' in radarname:
# # urllib.request.urlretrieve(f'https://radar.weather.gov/ridge/lite/CONUS-LARGE_loop.gif?{random()}',f'XenoRadar_{radarname}_{curdate}_{curtime}')
# loopname = ('CONUS-LARGE')
# elif 'addkarg1' in radarname:
# loopname = (f'K{radarname}')
# print ("shit!") # testing lmfao
# # the commented following is deprecated
# # urllib.request.urlretrieve(f'https://radar.weather.gov/ridge/lite/{loopname}_loop.gif?{random()}',f'data/radar/{imgname}')
# wget.download(f'https://radar.weather.gov/ridge/lite/{loopname}_loop.gif?{random.random()}',f'data/radar/{imgname}')
# # wget.download(f'https://radar.weather.gov/ridge/lite/{loopname}_loop.gif?{randomnum}',f'data/radar/{imgname}')
# # check if the file was downloaded
# if os.path.isfile(f'data/radar/{imgname}'):
# print(f'Cog_Radar: file {imgname} was downloaded!!')
# filepath = (f'data/radar/{imgname}')
# return filepath
# else:
# print("Cog_Radar: error has occurred")
# # send to the bitchy uploader (caution:sexy)
# # self.radarupload(f'{filepath}')
# async def radarupload(self,uploadimage):
# # uploadfile = self.filepath
# print("fuck!") # more testing lmao
# print(f'{self.filepath} this thingy should be ok')
# # await ctx.send(file=discord.File(f'{self.filepath}'))
# return uploadimage
# checks args for specific terms
# def argCheck(arg1, arg2):
# if "NATL" in arg1:
# downloadImage('conus')
#
# if arg1.len() == '3':
# addkarg1 = ('K'+arg1)
# downloadImage(addkarg1)
# else:
# downloadImage(arg1)
def initFolder():
if not os.path.exists("data/radar"):
print("Cog_Radar: radar image folder wasn't found, creating it")
os.makedirs("data/radar")
else:
print("Cog_Radar: radar image folder exists, we jud")
async def setup(bot):
initFolder()
await bot.add_cog(Radar(bot))
print (f'Cog_Radar: Was initialized {curdate}@{curtime}')

50
cogs/sameencode.py Normal file
View File

@ -0,0 +1,50 @@
import json
# from this import d
import discord
import time
import os
from discord.ext import commands
## Xeno Discord PY Bot
### same encoder
extname = f'SameEncoder'
initcurtime = time.localtime()
curtime = (f'{initcurtime.tm_hour}{initcurtime.tm_min}{initcurtime.tm_sec}')
curdate = (f'{initcurtime.tm_year}{initcurtime.tm_mon}{initcurtime.tm_mday}')
fnameformat = (f'XenoSAME_{curdate}_{curtime}.wav')
class SameEncoder(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='sameencode', pass_context=True)
async def sameencode(self, ctx, arg):
print(f"Cog_{extname}: encoding same message! {arg} for user {ctx.message.author.name}")
# await ctx.send(f"(for debugging only!!) Cog_{extname}: encoding same message! {arg} for user {ctx.message.author.name} (filename:")
os.system(f'python extensions/same.py --code "{arg}" --outfile "data/{extname}/{fnameformat}" >> data/{extname}/samepy_{curdate}_{curtime}.txt')
if not os.path.exists(f'data/{extname}/XenoSAME_{curdate}_{curtime}.wav'):
print(f'Cog_{extname}: same encoding failed! @ {curdate} {curtime}')
else:
print(f"Cog_{extname}: encoded at {curtime} on {curdate}, sending to channel user requested this in")
# await ctx.send(f"(for debugging only!!) Cog_{extname}: encoded at {curtime} on {curdate}, sending to channel user requested this in")
await ctx.reply(file=discord.File(f'data/{extname}/XenoSAME_{curdate}_{curtime}.wav'))
#encoder telemetry log
encodelog = open("data/SameEncoder/encoder.log", "a")
encodelog.write(f"Cog_{extname}: {curdate} @ {curtime}: {ctx.message.author} in {ctx.guild.name} ({ctx.guild.id}) encoded {arg}")
encodelog.close()
def initFolder():
if not os.path.exists(f"data/{extname}"):
print(f"Cog_{extname}: sameencode data folder wasn't found, creating it")
os.makedirs(f"data/{extname}")
else:
print(f"Cog_{extname}: {extname} data folder exists, we jud")
async def setup(bot):
initFolder()
print(f'Cog_SameEncoder was initialized')
await bot.add_cog(SameEncoder(bot))

38
cogs/slashcmds.py Normal file
View File

@ -0,0 +1,38 @@
import json
import discord
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import is_owner
if __name__ == "__main__":
print("This is a cog (addon) for the Xeno Discord bot. This file cannot be run standalone.")
exit()
## Xeno Discord PY Bot
### Slash Commands (test?)
extname = (f'SlashCmds')
class SlashCmds(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name='syncslash')
@is_owner()
async def syncslash(self, ctx):
synced = await ctx.bot.tree.sync()
await ctx.reply(f"{len(synced)} slash commands were synced successfully.")
# @commands.hybrid_command()
# async def slashdebug(ctx, name):
# await ctx.send(f"Showing tag: {name}")
@app_commands.command(name="slashdebug2", description="Tests slash command functionality- DEDICATED")
async def slashdebug(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message(f"You are super neat (dedicated command) :)")
#@app_commands.command(name="input",)
async def setup(bot):
print(f'Cog_{extname} was initialized')
await bot.add_cog(SlashCmds(bot))

15
cogs/svrspeccom.py Normal file
View File

@ -0,0 +1,15 @@
import json
import discord
from discord.ext import commands
## Xeno Discord PY Bot
### Server Specific Commands
class SpecificComm(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def setup(bot):
print(f'Cog_SpecificComm was initialized')
await bot.add_cog(SpecificComm(bot))

46
cogs/sysinfo.py Normal file
View File

@ -0,0 +1,46 @@
import json
import discord
import platform
import socket
import psutil
from discord.ext import commands
## Xeno Discord PY Bot
### System Info
if __name__ == "__main__":
print("This is a cog (addon) for the Xeno Discord bot. This file cannot be run standalone.")
exit()
class SysInfo(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='sysinfo')
async def sysinfocmd(self, ctx):
# await ctx.send(f'Please wait...')
#general stuff
embed=discord.Embed(title="Xeno System Information", description="see wot xeno's running on!")
embed.set_thumbnail(url="https://iraven.net/siteimg/xenobot.png")
embed.add_field(name='python (snek!) version', value=f'{platform.python_version()}', inline=True)
# embed.add_field(name='bot software version', value=f'{botversion}', inline=True)
embed.add_field(name='system hostname',value=f'{platform.node()}',inline=True)
embed.add_field(name='system os',value=f'{platform.system()}',inline=True)
#different routines for oses
if 'Windows' in platform.system():
# do windows shit here
embed.add_field(name='windows version',value=f'{platform.system()} {platform.win32_ver()[0]} {platform.win32_edition()} (NT Build {platform.win32_ver()[1]})', inline=False)
print (f'Cog_SysInfo: ur on windows bitch get a mac /s')
elif 'Linux' in platform.system():
# do linux shit here
embed.add_field(name ='linux version',value=f'{platform.system()} {platform.version()}')
print("Cog_SysInfo: sdfasdf")
await ctx.send(embed=embed)
async def setup(bot):
print(f'Cog_SysInfo initializing...')
await bot.add_cog(SysInfo(bot))
print(f'Cog_SysInfo was initialized')

78
cogs/test.py Normal file
View File

@ -0,0 +1,78 @@
import json
import discord
import time
import asyncio
from typing import Union
from discord.ext import commands
## Xeno Discord PY Bot
### Testing Commands
if __name__ == "__main__":
print("This is a cog (addon) for the Xeno Discord bot. This file cannot be run standalone.")
exit()
class Testing(commands.Cog):
def __init__(self, bot):
self.bot = bot
# args
@commands.command(name='testargs', pass_context=True)
async def testargs(self, ctx, arg1, arg2):
await ctx.send(f'{arg1} and {arg2} was sent!')
@commands.command(name='embedtest', pass_context=True)
async def embed(self, ctx):
embed=discord.Embed(title="embed testing!", description="you're a cute pone :3")
embed.set_thumbnail(url="https://iraven.net/siteimg/deioxpk-32.png")
await ctx.send(embed=embed)
@commands.command(name='botlogtest', pass_context=True)
async def botlogtest(self, ctx, arg):
print(arg)
logchnl = commands.Bot.get_channel('761854845283860531')
logchnl.send(f'test :3')
logchnl.send(f'{arg}')
@commands.command(name='ping2')
async def ping2(self, ctx, arg):
argms = (f'{arg * 100}')
await ctx.channel.send(f'Pinging {ctx.message.author.name} every {argms} ms...')
time.sleep({arg})
await ctx.channel.send(f'Tink! {commands.bot.latency * {argms}} ms')
time.sleep({arg})
await ctx.channel.send(f'Tink! {commands.bot.latency * {argms}} ms')
time.sleep({arg})
await ctx.channel.send(f'Tink! {commands.bot.latency * {argms}} ms')
@commands.command(name='uploadtest', description='tests upload')
async def uploadtest(self,ctx):
print("upload test command was run, testing upload capabilities")
await ctx.reply(file=discord.File(f'data/test/xeno_wave.gif'))
await ctx.send(f'if you see the above image, this actually fucking worked LOL')
# @commands.command(name='reactiontest', description='tests reaction for verif')
# async def reactiontest(self, ctx):
# reactions = ['\U+26A0']
# # initmsg = await ctx.send(f'{ctx.author}- react with :warning: on this message')
# for i in reactions:
# await ctx.add_reaction(i)
# @commands.Bot.event
# async def on_raw_reaction_add(payload):
# channel = commands.Bot.get_channel(payload.channel_id)
# message = await channel.fetch_message(payload.message_id)
# guild = commands.Bot.get_guild(payload.guild_id)
# member = guild.get_member(payload.user_id)
# reaction = discord.utils.get(message.reactions, emoji=payload.emoji.name)
# # only work if client
# if payload.user_id == commands.Bot.user.id:
# return
# if payload
async def setup(bot):
print(f'Cog_Testing was initialized')
await bot.add_cog(Testing(bot))

83
cogs/verification.py Normal file
View File

@ -0,0 +1,83 @@
import json
import discord
import time
import os
from discord.ext import commands
# from discord.utils import get
from discord.ext.commands import has_permissions, CheckFailure
## Xeno Discord PY Bot
### verification
extname = 'Verification'
initcurtime = time.localtime()
curtime = (f'{initcurtime.tm_hour}{initcurtime.tm_min}{initcurtime.tm_sec}')
curdate = (f'{initcurtime.tm_year}{initcurtime.tm_mon}{initcurtime.tm_mday}')
# reactions = ['\U+26A0']
# Load in server verif channels json
with open("./data/verification/servers.json", "r") as serversjsonFile:
verifservers = json.load(serversjsonFile)
class Verification(commands.Cog):
def __init__(self, bot):
self.bot = bot
# @commands.command(name='verify',description='verifies a user using roles to enter a server')
# async def verification(self, ctx):
# if (f'{ctx.message.guild.id}') in verifservers:
# print(f'{ctx.message.guild.id} was found in verifservers json')
# verifchannel = verifservers[f"{ctx.message.guild.id}"]
# else:
# print(f'{ctx.message.guild.id} was not found in verifservers json')
# verifchannel = "verification"
# verif_msg_id = ctx.message.id
# await ctx.message.add_reaction("⚠")
# @commands.Cog.listener()
# async def on_raw_reaction_add(self, payload):
# guild = self.bot.get_guild(payload.guild_id)
# role = discord.utils.get(guild.roles, name="Member")
# await payload.member.add_roles(role, reason=f"{payload.member.name} verified by Xeno (automated)", atomic=True)
# await payload.message.delete()
async def getVerificationCh(self, ctx):
for server in verifservers:
if (f'{ctx.message.guild.id}') in server:
print(f'{ctx.message.guild.id} was found in verifservers json')
verifchannel = verifservers[f"{ctx.message.guild.id}"]
else:
print(f'{ctx.message.guild.id} was not found in verifservers json')
verifchannel = "verification"
return verifchannel
async def telemLog(self, name, id, gname, gid):
#verification telemetry log
veriftelem = open("data/verification/verif.log", "a")
veriftelem.write(f"Cog_{extname}: successfully verified user {name} ({id}) in {gname} ({gid}) at {curtime} {curdate}")
veriftelem.close()
@commands.command(name="verify", description="verifies a user using roles to enter a server")
async def verifcmd(self, ctx):
# check if command was sent in non-verification channel, and don't do anything if so
verifchannel = self.getVerificationCh()
if ctx.channel.name not in verifchannel:
print("Message not sent in verification channel, temporary abort until i send a message.")
msgchannel = discord.utils.get(ctx.guild.channels, name=verifchannel)
msgchannelid = msgchannel.id
msgchannel.send(f"Test - your message wasn't sent in the verification channel of this server, {verifchannel}")
# https://stackoverflow.com/questions/65127487/how-to-make-a-reaction-role-command-with-discord-py
async def setup(bot):
print(f'Cog_{extname} was initialized')
# await bot.add_cog(Verification(bot))

193
extensions/same.py Normal file
View File

@ -0,0 +1,193 @@
import numpy as np
from scipy.io import wavfile
import random
import sys
import subprocess # to play the resulting wave file
import datetime # EAS alerts are heavily dependent on timestamps so this makes it easy to send a thing now
import argparse
# NicksMadScience same eas encoder was modified by iRaven @ iravenhome.net (github.com/iraven4522)
# version 0.2? to add a custom outfile path. :D
# parse command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--playaudiolive", "-pal", nargs='?', default=-1)
parser.add_argument("--code", "-c", nargs='?', default="none")
parser.add_argument("--outfile","-o", nargs='?', default="same.wav")
args = parser.parse_args()
######## CONFIG / constants ########
markBitFrequency = 2083 + (1/3)
spaceBitFrequency = 1562.5
print (args)
fs = 43750
# t = 1.0 / (520 + (5/6))
# f = 2083.33333
samples = np.zeros(0)
def markBit():
global markBitFrequency
# f = 2083.33333
f = markBitFrequency
t = 1.0 / (520 + (5/6))
samples = np.arange(t * fs) / fs
roffle = np.sin(2 * np.pi * f * samples)
return roffle * 0.8
def spaceBit():
global spaceBitFrequency
# f = 1562.5
f = spaceBitFrequency
t = 1.0 / (520 + (5/6))
samples = np.arange(t * fs) / fs
return np.sin(2 * np.pi * f * samples)
signal = np.zeros(20000)
def byte(the_byte):
sys.stdout.write(the_byte)
sys.stdout.write(" ")
byte_data = np.zeros(0)
for i in range(0, 8):
if ord(the_byte) >> i & 1:
sys.stdout.write("1")
byte_data = np.append(byte_data, markBit())
else:
sys.stdout.write("0")
byte_data = np.append(byte_data, spaceBit())
sys.stdout.write("\n")
sys.stdout.flush()
return byte_data
def extramarks(numberOfMarks):
"""SAGE encoders seem to add a few mark bits at the beginning and end"""
byte_data = np.zeros(0)
for i in range(0, numberOfMarks):
byte_data = np.append(byte_data, markBit())
return byte_data
def preamble():
byte_data = np.zeros(0)
for i in range(0, 16):
byte_data = np.append(byte_data, markBit())
byte_data = np.append(byte_data, markBit())
byte_data = np.append(byte_data, spaceBit())
byte_data = np.append(byte_data, markBit())
byte_data = np.append(byte_data, spaceBit())
byte_data = np.append(byte_data, markBit())
byte_data = np.append(byte_data, spaceBit())
byte_data = np.append(byte_data, markBit())
return byte_data
# ZCZC-WXR-RWT-020103-020209-020091-020121-029047-029165-029095-029037+0030-1051700-KEAX/NWS
# code = "ZCZC-EAS-RMT-011000+0100-2141800-SCIENCE-"
# code = "ZCZC-WXR-TOR-000000+0030-2142200-SCIENCE -"
# code = "ZCZC-PEP-EAN-000000+0400-2142350-SCIENCE -"
# control string
# code = "ZCZC-EAS-RMT-011000+0100-2142200-KMMS FM -"
# useful FIPS codes
# 000000 - the whole fucking united states
# 024031 - silver spring, md / montgomery county
# 011001 - district of columbia
# EAS alerts are heavily dependent on timestamps so this makes it easy/fun to send a thing now
sameCompatibleTimestamp = datetime.datetime.now().strftime("%j%H%M")
# known good
# OH SHIT it's all time-dependent
# which i can now do since the time works on the box
#code = "ZCZC-PEP-EAN-000000+0400-" + sameCompatibleTimestamp + "-SCIENCE -" # nuclear armageddon (or some other form of "we are all likely to die")
# code = "ZCZC-PEP-EAT-000000+0400-" + sameCompatibleTimestamp + "-SCIENCE -" # nuclear armageddon (or some other form of "we are all likely to die")
# code = "ZCZC-PEP-EAT-000000+0400-2142350-SCIENCE -" # lol jk no nuclear armageddon
code = "ZCZC-WXR-TOR-024031+0030-" + sameCompatibleTimestamp + "-SCIENCE -" # tornado warning, silver spring, md
# code = "ZCZC-WXR-SVR-024031+0030-2142200-SCIENCE -" # severe thunderstorm warning, silver spring, md
# code = "ZCZC-WXR-EVI-024031+0030-" + sameCompatibleTimestamp + "-SCIENCE -" # evacuation immediate!!, silver spring, md
# code = "ZCZC-WXR-FFW-024031+0030-2150021-SCIENCE -"
# testing
# code = "ZCZC-CIV-LAE-024031+0030-2150022-SCIENCE -"
# code = "ZCZC-CIV-CDW-024031+0400-" + sameCompatibleTimestamp + "-SCIENCE -"
# code = "ZCZC-PEP-EAN-024031+0030-" + sameCompatibleTimestamp + "-SCIENCE -"
# code = "ZCZC-ROFL-WTF-012345+0000-YO WADDUP MOTHAFUCKAZ="
code = args.code
for i in range(0, 3):
# signal = np.append(signal, extramarks(10))
signal = np.append(signal, preamble())
# turn each character into a sequence of sine waves
for char in code:
signal = np.append(signal, byte(char))
# signal = np.append(signal, extramarks(6)) # ENDEC might not be as picky about this as I once thought
signal = np.append(signal, np.zeros(43750)) # wait the requisite one second
# EOM (3x)
for i in range(0, 3):
# signal = np.append(signal, extramarks(10))
signal = np.append(signal, preamble())
for char in "NNNN": # NNNN = End Of Message
signal = np.append(signal, byte(char))
# signal = np.append(signal, extramarks(6))
signal = np.append(signal, np.zeros(43750)) # wait the requisite one second
signal *= 32767
signal = np.int16(signal)
wavfile.write(f'{args.outfile}', fs, signal)
if args.playaudiolive == "1":
subprocess.call("afplay same.wav", shell=True)

20
extensions/svrspeccom.py Normal file
View File

@ -0,0 +1,20 @@
import json
import discord
import requests
import shutil
from discord.ext import commands
## Xeno Discord PY Bot
### Radar Cog and Functionality
#make a cog.
class Radar(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='radar', pass_context=True)
async def radarget(ctx, *args):
print (f'stuff')
def setup(bot):
bot.add_cog(Radar(bot))

171
main.py Normal file
View File

@ -0,0 +1,171 @@
#Main.py
import os
import sys
import logging
import asyncio
from time import sleep
import discord
import platform
import json
import socket
import shutil
import time
#from python-dotenv import load_dotenv
from discord.ext import commands
from discord.ext.commands import is_owner
# Discord Xeno Bot in Python, Proj started 4/30/22
botversion = "0.0.2"
botbuilddate = "06/14/23"
# Load in main settings json
with open("./settings.json", "r") as configjsonFile:
botconfig = json.load(configjsonFile)
TOKEN = botconfig["TOKEN"]
OWNERID = botconfig["OWNER_ID"]
STATUS = botconfig["ACTIVITY"]
BOTLOGCHNL = botconfig["botlogchannel"]
initcurtime = time.localtime()
curtime = (f'{initcurtime.tm_hour}{initcurtime.tm_min}{initcurtime.tm_sec}')
curdate = (f'{initcurtime.tm_year}{initcurtime.tm_mon}{initcurtime.tm_mday}')
# Configure logging
logging.basicConfig(filename=f"PythonXeno_{curdate}.log",
format='%(asctime)s %(levelname)s %(message)s',
filemode='a')
log = logging.getLogger()
log.setLevel(logging.DEBUG)
logging.getLogger("urllib3").setLevel(logging.WARNING) # fuck urllib3 for making excessive logs in TranstarArchive
logging.getLogger("discord").setLevel(logging.WARNING) # wtf discord making the log file massive with shit
#load_dotenv()
#client = discord.Client()
#Defining bot v
bot = commands.Bot(command_prefix='i!',intents=discord.Intents.all())
print (f'Xeno Discord PY Bot- Version {botversion}')
print (f'Built on VSCode. Created by iRaven.')
print (f'Currently running on these specifications:')
print (f'{platform.machine()} - {platform.architecture()} {platform.processor()}')
print (f'Connecting to Discord...')
# Critical methods
## Loading any cogs found (CRITICAL)
async def botPlugins(eaction):
if eaction == "load":
print('Now loading any cogs in /cogs directory....')
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}") # :-3
print('Extensions were loaded c:')
elif eaction == "unload":
print('Now unloading any cogs in /cogs directory....')
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.unload_extension(f"cogs.{filename[:-3]}") # :-3
## Bot logging message to #xeno-bot-log
async def botLog(logmsg):
logchnl = bot.get_channel(761854845283860531)
print(f'Sent message to {logchnl.name}:{logmsg}')
# await logchnl.send(f'test :3')
await logchnl.send(f'{logmsg}')
## idk what the fuck this is
def commandLog(cmdnm):
print(f'Command was used: {cmdnm}')
@bot.event
async def on_ready():
print(f'{bot.user} is succesfully logged in with the current token.')
await bot.change_presence(activity=discord.Game(name=STATUS))
await botPlugins("load")
guild_count = 0
print ("Looking for servers:")
for guild in bot.guilds:
guild_count = guild_count + 1
print(f"Server found- {guild.id} / {guild.name}")
print("Currently in " + str(guild_count) + " servers")
print(f'Current ping to Discord servers: {bot.latency * 1000} ms')
synced = await bot.tree.sync()
print(f"{len(synced)} slash commands were synced successfully")
await botLog(f"Xeno is online- started {curdate} {curtime}")
# commands that always exist (basic func)
@bot.command(name='test')
async def test(ctx, arg):
await ctx.channel.send(f'Hewwo {arg} :3')
@bot.command(name='ping')
async def ping(ctx):
print(f'Manual ping sent-Current ping to Discord servers: {bot.latency * 1000} ms')
await ctx.channel.send(f'Tink! {bot.latency * 1000} ms')
@bot.command(name='hi')
async def ping(ctx):
await ctx.channel.send(f'Hewwo {ctx.message.author.name} :3')
# Bot Administration Commands below
@bot.command(name='shutdown')
@is_owner()
async def botshutdown(ctx):
print("Bot owner user requested bot shutdown NOW!")
print("The system is going down NOW!")
await ctx.reply(f"<a:loading_yt:1119526286621159555> The system is going down NOW! - Shutting down...")
bot.close() # i guess?
await botPlugins("unload") # unloads any cogs
print("Bot shutdown time has arrived")
await exit()
@bot.command(name='reloadexts')
@is_owner()
async def reloadcogs(ctx):
print("Bot owner user requested to reload all cogs")
await ctx.reply(f"<a:loading_yt:1119526286621159555> Reloading all extensions...")
print("Reloading all cogs now")
await botPlugins("unload")
time.sleep(1) # wait a second
await botPlugins("load")
await ctx.reply("Extensions reloaded successfully.")
# Slash Commands (more for testing as of 2023/06)
@bot.tree.command(name= "slashdebug", description="Tests slash command functionality")
async def slashdebug(interaction: discord.Interaction):
await interaction.response.send_message(f"You are super neat :)")
@bot.command(name='about')
async def aboutbot(ctx):
embed=discord.Embed(title="Xeno Bot Information", description="you're a cute pone :3")
embed.add_field(name='XenoBot Version',value=f'{botversion}',inline=True)
embed.add_field(name='Build Date',value=f'{botbuilddate}',inline=True)
embed.add_field(name='Python Version',value=f'{platform.python_version()}')
embed.add_field(name='Originally Created',value='September 2018')
embed.add_field(name='Code Rewritten in JS',value='December 2018')
embed.add_field(name='Current Code Rewritten in Python (from scratch!)',value='May 2022')
embed.add_field(name='Bot Owner',value='iRaven (Special Kudos to ItzGabe25 for most of the js code, in use until June 2023)')
embed.set_thumbnail(url="https://iravenhome.net/siteimg/xenobot.png")
await ctx.send(embed=embed)
# This stuff right here breaks everything oops lmao
#@bot.event
#async def on_message(message):
# if message.content == "test":
# await message.channel.send("helo")
# if message.content == "wubs":
# await message.channel.send("wubs?! where?!")
@bot.listen('on_message')
async def wordresponder(message):
if message.content == "test":
await message.channel.send("helo")
if message.content == "wubs":
await message.channel.send("wubs?! where?!")
bot.run(TOKEN)

5
settings_example.json Normal file
View File

@ -0,0 +1,5 @@
{
"TOKEN": "yourtokenhere",
"OWNER_ID": "user id of bot owner here"
}