TranslationBot / app.py
NihalGazi's picture
Update app.py
cd371ad verified
import discord
from discord.ext import commands
import threading
import gradio as gr
import asyncio
import requests
import urllib.parse
from dotenv import load_dotenv
import os
# Set up intents - message_content is required to fetch message text
intents = discord.Intents.default()
intents.messages = True
intents.reactions = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
# Mapping flag emojis to their language names
flag_to_language = {
"๐Ÿ‡ฌ๐Ÿ‡ง": "English",
"๐Ÿ‡ซ๐Ÿ‡ท": "French",
"๐Ÿ‡ฉ๐Ÿ‡ช": "German",
"๐Ÿ‡ช๐Ÿ‡ธ": "Spanish",
"๐Ÿ‡ฎ๐Ÿ‡น": "Italian",
"๐Ÿ‡ท๐Ÿ‡บ": "Russian",
"๐Ÿ‡ฏ๐Ÿ‡ต": "Japanese",
"๐Ÿ‡จ๐Ÿ‡ณ": "Chinese",
"๐Ÿ‡น๐Ÿ‡ท": "Turkish",
# Add more flags and language names as needed
}
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.event
async def on_raw_reaction_add(payload):
# Ignore reactions by the bot itself
if payload.user_id == bot.user.id:
return
emoji = str(payload.emoji)
if emoji in flag_to_language:
target_lang = flag_to_language[emoji]
channel = bot.get_channel(payload.channel_id)
if channel is None:
print("Channel not found")
return
try:
# Fetch the full message to access its content
message = await channel.fetch_message(payload.message_id)
except Exception as e:
print(f"Error fetching message: {e}")
return
original_text = message.content
if not original_text:
print("Message content is empty!")
return
# Build the translation prompt using the target language
prompt = (
f'Translate "{original_text}" to {target_lang}. '
"Write only and only the translated text, no need for explanation or anything."
)
encoded_prompt = urllib.parse.quote(prompt)
server = os.getenv("api")
url = f"{server}{encoded_prompt}"
print(f"GET {url}")
try:
# Run the blocking GET request in a thread so as not to block the event loop.
response = await asyncio.to_thread(requests.get, url, timeout=10)
response.raise_for_status()
translated_text = response.text.strip()
print(f"API response: {translated_text}")
if not translated_text:
translated_text = "[No translation returned]"
except Exception as e:
print(f"Error during GET request: {e}")
translated_text = "[Error translating text]"
# Reply to the original message so that it is tagged
await message.reply(f"{translated_text}")
def run_discord_bot():
bot.run(os.getenv("token")) # Replace with your actual token
# Run the Discord bot in a separate daemon thread
threading.Thread(target=run_discord_bot, daemon=True).start()
# Gradio interface function (simple echo interface)
def process_input(text):
if not text.strip():
return "OK"
return text
iface = gr.Interface(
fn=process_input,
inputs=gr.Textbox(label="Enter something"),
outputs=gr.Textbox(label="Output")
)
iface.launch()