Download main.py from An7onchik/MilkiWay: direct link, hf CLI and curl.
- Browser
- Download file 2.69 kB
-
https://huggingface.co/spaces/An7onchik/MilkiWay/resolve/main/main.py
- Command line
-
hf download hf://spaces/An7onchik/MilkiWay/main.py
-
curl -L -o main.py https://huggingface.co/spaces/An7onchik/MilkiWay/resolve/main/main.py
2.69 kB
| import os | |
| import telebot | |
| import requests | |
| import io | |
| from openai import OpenAI | |
| from flask import Flask, request | |
| # Код сам автоматически заберет все данные из настроек Settings | |
| TG_TOKEN = os.environ.get("TG_TOKEN") | |
| TEXT_AI_API_KEY = os.environ.get("TEXT_AI_API_KEY") | |
| HF_TOKEN = os.environ.get("HF_TOKEN") | |
| SPACE_URL = os.environ.get("SPACE_URL") | |
| bot = telebot.TeleBot(TG_TOKEN, threaded=False) | |
| ai_client = OpenAI(base_url="https://groq.com", api_key=TEXT_AI_API_KEY) | |
| app = Flask(__name__) | |
| def receive_update(): | |
| json_string = request.get_data().decode('utf-8') | |
| update = telebot.types.Update.de_json(json_string) | |
| bot.process_new_updates([update]) | |
| return "!", 200 | |
| def homepage(): | |
| return "Бот активен!", 200 | |
| # 1. Команда для картинок | |
| def handle_image_generation(message): | |
| prompt = message.text.replace('/draw', '').replace('/image', '').strip() | |
| if not prompt: | |
| bot.reply_to(message, "Укажите, что нарисовать после команды. Пример: /draw кот") | |
| return | |
| status_msg = bot.reply_to(message, "🎨 Рисую картинку Flux...") | |
| try: | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} | |
| response = requests.post("https://huggingface.co", headers=headers, json={"inputs": prompt}) | |
| if response.status_code == 200: | |
| bot.delete_message(message.chat.id, status_msg.message_id) | |
| bot.send_photo(message.chat.id, io.BytesIO(response.content), reply_to_message_id=message.message_id) | |
| else: | |
| bot.edit_message_text("Ошибка ИИ-картинок.", message.chat.id, status_msg.message_id) | |
| except Exception as e: | |
| bot.edit_message_text("Не удалось сгенерировать изображение.", message.chat.id, status_msg.message_id) | |
| # 2. Текстовый чат | |
| def handle_text_chat(message): | |
| try: | |
| completion = ai_client.chat.completions.create( | |
| model="llama3-8b-8192", | |
| messages=[{"role": "user", "content": message.text}] | |
| ) | |
| bot.reply_to(message, completion.choices.message.content) | |
| except Exception as e: | |
| bot.reply_to(message, "Ошибка ИИ при генерации ответа.") | |
| if __name__ == "__main__": | |
| # Чистим старый адрес и ставим новый из настроек | |
| bot.remove_webhook() | |
| bot.set_webhook(url=f"{SPACE_URL}/{TG_TOKEN}") | |
| app.run(host="0.0.0.0", port=7860) | |