Compare commits

..
9 Commits
2 changed files with 100 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
import os
import discord
from discord.ext import commands
from openai_interaction.image_recognition_test import image_recognition
# Загружаем токен из переменной среды
TOKEN = os.getenv('SCREAMING_OPOSSUM')
# Создаем клиент с префиксом (не обязателен для слэш-команд)
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
# region Bot Stuff
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} command(s).')
except Exception as e:
print(f'Failed to sync commands: {e}')
@bot.tree.command(name='hello', description='Screams at you!')
async def hello_command(interaction: discord.Interaction):
async with interaction.channel.typing():
await interaction.response.send_message('AAAAAAAAAAAAAAAAAAAAA!')
@bot.event
async def on_message(message: discord.Message):
if message.author == bot.user:
return
if message.attachments and bot.user in message.mentions:
async with message.channel.typing():
message_attachments = [
{'filename': i_attachment.filename, 'url': i_attachment.url} for i_attachment in message.attachments
]
await message.channel.send(await image_recognition(message.content, message_attachments))
await bot.process_commands(message)
# endregion
if __name__ == '__main__':
if TOKEN is None:
raise RuntimeError('Environment variable SCREAMING_OPOSSUM is not set')
bot.run(TOKEN)
@@ -0,0 +1,48 @@
import asyncio
from openai import OpenAI
client = OpenAI()
SUPPORTED_IMAGE_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.webp', '.gif')
async def image_recognition(content: str, files: list[dict[str: str]]) -> str:
input_data = [{'type': 'input_text', 'text': content}]
input_data.extend(
[
{
'type': 'input_image',
'image_url': i_url.get('url'),
}
for i_url in files if i_url.get('filename').lower().endswith(SUPPORTED_IMAGE_EXTENSIONS)
]
)
response = client.responses.create(
model='gpt-4.1-mini',
input=[{
'role': 'user',
'content': input_data,
}],
)
return response.output_text
if __name__ == '__main__':
data = {
'content': 'What\'s on these images?',
'files': [
{
'filename': 'Вы_продоёте_рыбов.jpg',
'url': 'https://upload.wikimedia.org/wikipedia/ru/8/8a/%D0%92%D1%8B_%D0%BF%D1%80%D0%BE%D0%B4%D0%BE%D1%91%D1%82%D0%B5_%D1%80%D1%8B%D0%B1%D0%BE%D0%B2.jpg',
},
{
'filename': 'Putin_and_Macron_meeting_with_a_large_table.jpg',
'url': 'https://upload.wikimedia.org/wikipedia/commons/a/a9/Putin_and_Macron_meeting_with_a_large_table.jpg',
},
{
'filename': 'shitty_pdf_file.pdf',
'url': 'https://example.com/shitty_pdf_file.pdf'
}
],
}
result = asyncio.run(image_recognition(**data))
print(result)