text to speech

This commit is contained in:
SpookyDervish
2025-10-25 08:06:17 +11:00
parent 22c84785d6
commit e0b991ce18

242
main.py
View File

@@ -1,9 +1,17 @@
import discord
import logging
import os
import time
import asyncio
import requests
import base64
import subprocess
import json
import ffmpeg
import pyttsx3
from datetime import timedelta
from dotenv import load_dotenv
from random import randint, choice
from random import randint, choice, random
load_dotenv()
@@ -13,6 +21,10 @@ handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w"
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
tts_engine = pyttsx3.init()
is_sleeping = False
crash_out_time = time.time()
mood = 5 # if this reaches 0 he snaps for at you lol
words = ["gleep", "glorp", "zorp", "gnarp", "gorg", "alien", "alienz", "goog", "slorp", "gorg"]
emojis = ["👽", "🔥", "🗣️"]
yes_no_answers = [
@@ -70,6 +82,161 @@ when_question_answers = [
"in so long you won't be alive anymore",
"later"
]
crash_out_responses = [
"...",
"the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end",
"https://tenor.com/view/susan-woodings-susan-woodings-the-walten-files-twf-gif-24185478",
"........",
". . . ",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"...",
"i was crazy once. they locked me in a room. a rubber room. a rubber room with rats. and rats make me crazy.",
"not. right. now.",
"GOD JUST SHUT UP, PLEASE. I BEG OF YOU"
]
async def send_tts_message(message: str, channel: discord.TextChannel):
tts_engine.save_to_file(message, "voice-message.mp3")
tts_engine.runAndWait()
await send_voice_message("voice-message.mp3", channel)
if os.path.exists("voice-message.mp3"): os.remove("voice-message.mp3")
async def send_voice_message(file_path: str, channel: discord.TextChannel):
bot_token = os.getenv('TOKEN')
# Convert MP3 to OGG (Opus) using ffmpeg
ogg_filename = "voice-message.ogg"
try:
subprocess.run([
"ffmpeg",
"-y",
"-i", file_path,
"-c:a", "libopus",
"-b:a", "64k",
"-ar", "48000",
ogg_filename
], check=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# Extract metadata using ffprobe
def get_audio_metadata(file_path):
""" Extracts audio duration and waveform data using ffprobe. """
audio = ffmpeg.probe(file_path)
# Generate a simple waveform (instead of real analysis)
waveform = base64.b64encode(os.urandom(256)).decode('utf-8')
return round(float(audio["format"]["duration"])), waveform
# Get required metadata
duration, waveform = get_audio_metadata(ogg_filename)
file_size = os.path.getsize(ogg_filename)
# Step 1: Request an upload URL
url = f"https://discord.com/api/v10/channels/{channel.id}/attachments"
headers = {
"Authorization": f"Bot {bot_token}",
"Content-Type": "application/json",
#"User-Agent": UserAgent().random
}
payload = {
"files": [{
"filename": "voice-message.ogg",
"file_size": file_size,
"id": 0
}]
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code != 200:
print("Failed to get upload URL:", response.text)
exit()
upload_data = response.json()["attachments"][0]
upload_url = upload_data["upload_url"]
uploaded_filename = upload_data["upload_filename"]
# Step 2: Upload the audio file
with open(ogg_filename, "rb") as file:
upload_response = requests.put(upload_url, headers={"Content-Type": "audio/ogg"}, data=file)
if upload_response.status_code != 200:
print("Failed to upload file:", upload_response.text)
exit()
# Step 3: Send the voice message
message_url = f"https://discord.com/api/v10/channels/{channel.id}/messages"
message_payload = {
"flags": 8192, # IS_VOICE_MESSAGE
"attachments": [{
"id": "0",
"filename": "voice-message.ogg",
"uploaded_filename": uploaded_filename,
"duration_secs": duration,
"waveform": waveform
}]
}
message_response = requests.post(message_url, headers=headers, json=message_payload)
print(message_response.status_code, f"Error Response: \n{json.dumps(message_response.text, indent=4, ensure_ascii=False)}" if message_response.status_code != 200 else "Upload Succesfull!")
finally:
if os.path.exists(ogg_filename): os.remove(ogg_filename)
async def sleep_cycle():
global is_sleeping
while True:
await asyncio.sleep(randint(300, 900)) # every 515 mins
if not is_sleeping and random() < 0.3: # 30% chance to fall asleep
is_sleeping = True
await client.change_presence(status=discord.Status.idle)
print("💤 Bot is sleeping...")
await asyncio.sleep(randint(60, 180)) # sleep 13 mins
if is_sleeping:
await client.change_presence(status=discord.Status.online)
is_sleeping = False
print("☀️ Bot woke up!")
async def increase_mood(message: discord.Message):
global mood
if mood == 0:
return
mood += 1
async def decrease_mood(message: discord.Message):
global mood
if mood == 0:
return
mood -= 1
if mood == 1:
await message.channel.send("i can't take this much longer")
if mood == 0:
crash_out_time = time.time()
await message.reply("I CANTZ TAEK IT ANYMOR!!!!")
await message.channel.send("https://tenor.com/view/crash-out-strangle-over-it-im-done-wtf-gif-5733066100478599257")
admin_role_id = 1412398091549675541
@@ -79,33 +246,72 @@ client = discord.Client(intents=intents)
@client.event
async def on_ready():
client.loop.create_task(sleep_cycle())
#channel = await client.fetch_channel(1431237413845340311)
#await send_voice_message("test.mp3", channel)
print("gleep glorp!!!!!! 👽👍")
@client.event
async def on_message(message: discord.Message):
global mood, is_sleeping
if time.time()-crash_out_time > 60:
mood = 5
if message.author == client.user:
return
for swear_word in swear_words:
if message.clean_content.lower().find(swear_word) != -1:
await message.reply("no swearing")
await message.channel.send("https://tenor.com/view/xenoverse-goku-super-saiyan-angry-dbz-gif-1416275111944307575")
return
if mood > 0:
for swear_word in swear_words:
if message.clean_content.lower().find(swear_word) != -1:
await message.reply("no swearing")
await message.channel.send("https://tenor.com/view/xenoverse-goku-super-saiyan-angry-dbz-gif-1416275111944307575")
await decrease_mood(message)
return
if client.user.mentioned_in(message):
response = ""
content = message.clean_content.removeprefix("@gleep glorp").lower().strip()
if content.find("wake up") != -1:
if is_sleeping:
is_sleeping = False
await message.reply("AAAAA oh. i am awaken :)")
await client.change_presence(status=discord.Status.online)
else:
await message.reply("i was not sleeps")
return
if is_sleeping:
if random() < 0.1:
await message.reply("💤 \*mumbles in sleep\*")
return
if mood <= 0:
await message.reply(choice(crash_out_responses))
return
if content.startswith("kill"):
if content == "kill yourself":
await message.reply(choice(sad_answers))
await decrease_mood(message)
return
else:
target = message.mentions[1]
if message.mention_everyone == True:
await message.reply("veri funni buckaroo :|")
return
if message.guild.get_role(admin_role_id) in message.author.roles:
try:
await message.mentions[1].timeout(timedelta(minutes=5))
await message.reply("ok")
await message.reply("deploying gleep glorp lazor off dume!!!!")
time.sleep(1)
await message.channel.send("targor aquire....")
time.sleep(2)
await message.channel.send("im jus kiddings!!! im still timing u out tho " + target.mention)
time.sleep(1)
await target.timeout(timedelta(minutes=5))
except IndexError:
await message.reply("you didn't say who to kill")
except discord.errors.Forbidden:
@@ -121,8 +327,14 @@ async def on_message(message: discord.Message):
if content.find("goon") != -1:
response = "gooning is not allowed you fucking weirdo"
await decrease_mood(message)
elif content.startswith("speak "):
content = content.removeprefix("speak ")
await send_tts_message(content, message.channel)
return
elif content.find("bad alien") != -1:
response = choice(sad_answers)
await decrease_mood(message)
elif content.find("good alien") != -1:
response = choice(happy_answers)
elif content.find("why") != -1:
@@ -133,16 +345,18 @@ async def on_message(message: discord.Message):
response = f"da rel alienz sai it was {choice(message.guild.members).mention}"
elif content.startswith("do ") or content.startswith("can ") or content.startswith("is ") or content.find("am ") != -1 or content.find("will ") != -1 or content.startswith("are ") or content.find("which") != -1 or content.find("would") != -1 or content.find("does") != -1 or content.startswith("should"):
response = choice(yes_no_answers)
elif content.find("ily") != -1 or content.find("i love you") != -1 or content.find("i like you") != -1:
response = "yay"
elif content.find("ihy") != -1 or content.find("i hate you") != -1 or content.find("i detest you") != -1 or content.find("i despise you") != -1 or content.find("i hate you") != -1 != -1 or content.find("screw you") != -1 or content.find("fuck you") != -1:
await message.reply(choice(sad_answers))
return
elif content.find("ily") != -1 or content.find("love you") != -1 or content.find("i like you") != -1:
response = choice(happy_answers)
await increase_mood(message)
elif content.find("ihy") != -1 or content.find("hate you") != -1 or content.find("detest you") != -1 or content.find("despise you") != -1 or content.find("hate you") != -1 != -1 or content.find("screw you") != -1 or content.find("fuck you") != -1:
response = choice(sad_answers)
await decrease_mood(message)
elif content.startswith("say "):
content = content.removeprefix("say ")
response = content
elif content.find("thanks") != -1 or content.find("thank you") != -1:
response = "no problem bro 😎"
await increase_mood(message)
else:
if randint(1, 10) != 1:
for _ in range(randint(1, 8)):