bot.py

Code used to for most of the backend of Orb AI.

import os as _os import sys as _sys import asyncio as _asyncio import re as _re from dotenv import load_dotenv as _load_dotenv import openai as _openai from twitchio.ext import commands as _commands from gtts import gTTS as _gTTS import platform as _platform

=== Load Environment Variables ===

_load_dotenv()

=== Retrieve Environment Variables ===

OPENAI_API_KEY = _os.getenv("OPENAI_API_KEY") TWITCH_OAUTH_TOKEN = _os.getenv("TWITCH_OAUTH_TOKEN") TWITCH_CHANNEL_NAME = _os.getenv("TWITCH_CHANNEL_NAME") BLOCKED_WORDS = _os.getenv("BLOCKED_WORDS", "")

=== Validate Environment Variables ===

def _validate_env_vars(): missing_vars = [] if not OPENAI_API_KEY: missing_vars.append("OPENAI_API_KEY") if not TWITCH_OAUTH_TOKEN: missing_vars.append("TWITCH_OAUTH_TOKEN") if not TWITCH_CHANNEL_NAME: missing_vars.append("TWITCH_CHANNEL_NAME")

if missing_vars:
    _sys.exit(f"Error: Missing environment variables: {', '.join(missing_vars)}")

_validate_env_vars()

=== Configure OpenAI ===

_openai.api_key = OPENAI_API_KEY

=== Configure Text-to-Speech ===

ENABLE_TTS = True # Enable TTS

=== TTS Function Using gTTS ===

def _speak(text: str): if text: try: print(f"[TTS] Converting text to speech: {text}") tts = _gTTS(text=text, lang='en', tld='co.uk') # Set to British English tts.save("output.mp3")

=== Content Filtering ===

def _get_blocked_words(): return [_word.strip().lower() for _word in BLOCKED_WORDS.split(',')] if BLOCKED_WORDS else []

BLOCKED_WORDS_LIST = _get_blocked_words()

def _is_message_allowed(message: str) -> bool: return not any(_word in message.lower() for _word in BLOCKED_WORDS_LIST)

=== Conversation History ===

conversation_history = {}

def _split_text(text, max_length=50): sentences = _re.split(r'(?<=[.!?]) +', text) chunks = [] current_chunk = ''

async def _generate_openai_response(channel: str, user: str, message: str) -> str: if not _is_message_allowed(message): return "I'm sorry, OrbAI does not tolerate that."

class _TwitchBot(_commands.Bot): def init(self): super().init( token=TWITCH_OAUTH_TOKEN, prefix="!", initial_channels=[f"#{TWITCH_CHANNEL_NAME.lower()}"] )

=== Main Entry Point ===

if name == "main": _bot = _TwitchBot() try: _bot.run() except KeyboardInterrupt: print("\n[Shutdown] Bot is shutting down...") except Exception as _e: print(f"[Error] Unexpected error: {_e}")

Last updated