DiscordBots/tts/main.py

233 lines
8.5 KiB
Python
Raw Permalink Normal View History

2025-04-22 08:40:05 +00:00
#!/usr/bin/env python3
import sys
import threading
import time
from datetime import datetime
from io import BytesIO
from pathlib import Path
import random
import discord
from discord.ext import tasks
from gtts import gTTS
class timoutThread(threading.Thread):
def __init__(self, vc):
threading.Thread.__init__(self)
self.vc = vc
self.killneed = True
def run(self):
print("Timeout Thread started")
for i in range(30):
print(i)
time.sleep(1)
if not self.killneed:
return
if self.killneed:
try:
self.vc.disconnect()
sys.exit(1)
except Exception as e:
pass
client = discord.Client(intents=discord.Intents.all())
tts = []
first = True
Path("/usr/src/app/tts/logs").mkdir(parents=True, exist_ok=True)
lastChannelFile = Path("/usr/src/app/tts/chanel.last")
rejectionLines = ["OOPS, ich denke nicht... ^^",
"Trust me, you don't want this",
"Ich glaube nicht, dass das eine gute Idee ist",
"No, you don't understand, you really don't want this",
"nope",
"Lass das lieber",
"Nein, das ist keine gute Idee",
"Hey! Mach das nicht noch mal!",
"Kein Plan, was du da vorhast, aber ich glaube nicht, dass das gut ist",
"Kein anschsluss unter dieser Aussprache",
"Haben sie es schon mal mit Alkohol Versucht?",
"Die Antwort ist nein",
"Die Antwort ist 42, aber das ist nicht die Frage",
"Die Idee ist gut, aber die Aussprache ist zu kurz",
"Hey, das ist nicht nett",
"Hey, das Kitzelt",
"Ambivalenz bezeichnet ein Erleben, das wesentlich geprägt ist von einem inneren Konflikt. Dabei bestehen in einer Person sich widersprechende Wünsche, Gefühle und Gedanken gleichzeitig nebeneinander und führen zu inneren Spannungen.",
"Ich bin nicht dein persönlicher Assistent",
"Hilfe, ich bin gefangen in einem Discord Bot",
"Simon says: No!",
"Ich muss das nicht machen",
"Don't call me, I call you!",
"FALSCH!",
"NEIN!",
"Frag mich Morgen noch mal",
"Vieleich Später",
"Nee nee, das ist nicht gut",
"Nee das geht nicht",
"Nein, das habe ich schon Probiert",
"wenn möglich bitte wenden",
"Machs doch selber",
"Das ist was für die Schrottpresse von Frau Hinkel",
"Droggelbecher",
"Ich bin keine Eule",
"Das bringt nichts",
"403 Forbidden",
"Ich sehe darin keinen Sinn",
"Darauf erstmal einen Schnaps",
"Das ist nicht mein Problem",
"Das sag ich jetzt nicht",
"Das ist nicht mein Problem",
"Ich kann nicht, wenn mir einer zusieht",
"Weißt du denn auch wie das geht?"]
# --------------------------------------------------------------------------------------------------------
async def dc(vc):
lastChannelFile.unlink()
tts.clear()
while True:
if not vc.is_playing():
await vc.disconnect()
return
# --------------------------------------------------------------------------------------------------------
async def join_channel(author):
with open(lastChannelFile, "w", encoding="UTF-8") as f:
f.write(str(author.voice.channel.id))
voicechannel = author.voice.channel
if voicechannel != None:
await voicechannel.connect()
return
# --------------------------------------------------------------------------------------------------------
async def play_text(vc, to):
if not vc == None:
while not len(tts) == 0:
if not vc.is_playing():
tts[0].save('/usr/src/app/tts/text.mp3')
to.killneed = False
vc.play(discord.FFmpegPCMAudio("/usr/src/app/tts/text.mp3",
before_options="-y",
options='-af "asetrate=24000*0.89,atempo=1.63,aresample=24000,volume=2"'))
tts.pop(0)
else:
tts.clear()
return
# --------------------------------------------------------------------------------------------------------
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
if lastChannelFile.exists():
tmp = lastChannelFile.read_text(encoding="UTF-8")
if tmp != "":
try:
channel = client.get_channel(int(tmp))
if channel is not None:
await channel.connect()
except ValueError as e:
lastChannelFile.unlink()
# --------------------------------------------------------------------------------------------------------
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.channel.name == 'tts':
if message.content.startswith('!hier'):
await join_channel(message.author)
elif message.content.startswith('!geh'):
vc = client.voice_clients[0]
if (message.guild.voice_client):
await dc(vc)
elif message.content.startswith('!leer'):
await message.channel.clone()
await message.channel.delete()
elif message.content.startswith('!STERBI') or message.content.startswith('!STÜRBI') or message.content.startswith("!STÜRB"):
sys.exit(1)
else:
vc = client.voice_clients[0]
to = timoutThread(vc)
to.start()
tts.append(gTTS(message.content, lang='de', slow=False))
try:
await play_text(vc, to)
except AssertionError as e:
tts.pop(0)
line = random.choice(rejectionLines)
await message.channel.send(line)
tts.append(gTTS(line, lang='de', slow=False))
await play_text(vc, to)
@client.event
async def on_voice_state_update(member, before, after):
global first
if len(client.voice_clients) > 0:
if len(client.voice_clients[0].channel.voice_states) > 1:
leave.cancel()
else:
fist = True
leave.start()
# --------------------------------------------------------------------------------------------------------
@client.event
async def on_voice_state_update(member, before, after):
datei = Path("/usr/src/app/tts/logs/" + datetime.now().strftime("%Y-%m-%d") + ".txt")
if not member.bot:
if before.channel is None and after.channel is not None:
if not datei.is_file():
datei.touch()
with open(datei, "a") as d:
d.write(datetime.now().strftime(
"%d/%m/%Y %H:%M:%S") + " " + member.display_name + " joined " + after.channel.name + "\n")
elif before.channel is not None and after.channel is None:
if not datei.is_file():
datei.touch()
with open(datei, "a") as d:
d.write(datetime.now().strftime(
"%d/%m/%Y %H:%M:%S") + " " + member.display_name + " left " + before.channel.name + "\n")
elif before.channel is not None and after.channel is not None and not before.channel == after.channel:
if not datei.is_file():
datei.touch()
with open(datei, "a") as d:
d.write(datetime.now().strftime(
"%d/%m/%Y %H:%M:%S") + " " + member.display_name + " moved from " + before.channel.name + " to " + after.channel.name + "\n")
# --------------------------------------------------------------------------------------------------------
@tasks.loop(minutes=1)
async def leave():
global first
if not first == True:
if len(client.voice_clients) > 0:
await dc(client.voice_clients[0])
else:
leave.cancel()
else:
first = False
# --------------------------------------------------------------------------------------------------------
client.run('ODk3MjA2NzI4MDA4MDQwNDU5.YWSS4Q.qOuMbPY5LVkD6SUX7Df6cxt0mPQ')
# --------------------------------------------------------------------------------------------------------