import twitchio
import openai
import pyttsx3
import time

# Twitch credentials
BOT_USERNAME = 'JotatoBot'
OAUTH_TOKEN = ''
CHANNEL_NAME = 'Jotatochips'

# Initialize OpenAI GPT-3 API
openai.api_key = ''

# Initialize Twitch bot
bot = twitchio.Client(token=OAUTH_TOKEN, initial_channels=[CHANNEL_NAME])

# Initialize text-to-speech engine
engine = pyttsx3.init()

# Initialize last request time
last_request_time = 120

# Event handler for when the bot is ready
@bot.event
async def event_ready():
    print(f"Bot connected to {CHANNEL_NAME}")

# Event handler for incoming messages
@bot.event
async def event_message(ctx):
    if ctx.author.name != BOT_USERNAME:  # Ignore messages sent by the bot itself
        if ctx.content.startswith('!askgpt'):
            question = ctx.content[len('!askgpt'):]
            response = generate_response(question)
            await ctx.channel.send(response)

# Function to generate response using GPT-3
def generate_response(question):
    # Perform offensive language detection
    if contains_offensive_language(question):
        return "Oops! Let's keep the chat friendly. Please refrain from using offensive language."

    # Generate response using GPT-3 API
    try:
        response = openai.Completion.create(
            engine="text-davinci-002",
            prompt=question,
            temperature=0.7,
            max_tokens=500
        )
        return response.choices[0].text.strip()
    except Exception as e:
        print(f"Error generating response: {e}")
        return "Oops! Something went wrong while generating the response."

# Function to detect offensive language
def contains_offensive_language(text):
    banned_words = ['fag', 'faggot', 'faggit', 'nigger', 'nigga', 'n1gger' , 'n1gg3r' ,'f@g' ,'chink', 'yellow face', 'cunt', 'dyke', 'dike', 'retard', 'retarded', 'coon', 'simp', 'virgin', 'incel', 'insel', 'hood rat', 'whore']
    for word in banned_words:
        if word in text.lower():
            return True
    return False

# Function to convert text to speech
def text_to_speech(text):
    engine.say(text)
    engine.runAndWait()

# Run the bot
try:
    bot.run()
except Exception as e:
    print("An error occurred:", e)