Spaces:
Running
Running
Upload telegram_bot.py with huggingface_hub
Browse files- telegram_bot.py +138 -0
telegram_bot.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Standalone Telegram Bot Worker for Kora AI Ecosystem.
|
| 3 |
+
Connects Telegram users directly to Kora Chat, Kora Coder 0.5B, and Kora Image Studio.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
1. Get a bot token from @BotFather on Telegram.
|
| 7 |
+
2. Set TELEGRAM_BOT_TOKEN="your_bot_token_here"
|
| 8 |
+
3. Run: python telegram_bot.py
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
import json
|
| 15 |
+
import urllib.parse
|
| 16 |
+
import urllib.request
|
| 17 |
+
from threading import Thread
|
| 18 |
+
|
| 19 |
+
if hasattr(sys.stdout, "reconfigure"):
|
| 20 |
+
sys.stdout.reconfigure(encoding="utf-8")
|
| 21 |
+
|
| 22 |
+
# Kora Gateway Endpoint
|
| 23 |
+
KORA_ENDPOINT = os.environ.get("KORA_ENDPOINT", os.environ.get("KORA_CUSTOM_ENDPOINT", "https://professorceo-kora-ai.hf.space")).rstrip("/")
|
| 24 |
+
BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()
|
| 25 |
+
|
| 26 |
+
def send_telegram_message(chat_id: int, text: str):
|
| 27 |
+
if not BOT_TOKEN:
|
| 28 |
+
return
|
| 29 |
+
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
|
| 30 |
+
try:
|
| 31 |
+
req_data = json.dumps({"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}).encode("utf-8")
|
| 32 |
+
req = urllib.request.Request(url, data=req_data, headers={"Content-Type": "application/json"})
|
| 33 |
+
urllib.request.urlopen(req, timeout=10)
|
| 34 |
+
except Exception:
|
| 35 |
+
try:
|
| 36 |
+
req_data = json.dumps({"chat_id": chat_id, "text": text}).encode("utf-8")
|
| 37 |
+
req = urllib.request.Request(url, data=req_data, headers={"Content-Type": "application/json"})
|
| 38 |
+
urllib.request.urlopen(req, timeout=10)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"β Error sending Telegram message: {e}", flush=True)
|
| 41 |
+
|
| 42 |
+
def send_telegram_photo(chat_id: int, photo_url: str, caption: str = ""):
|
| 43 |
+
if not BOT_TOKEN:
|
| 44 |
+
return
|
| 45 |
+
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendPhoto"
|
| 46 |
+
try:
|
| 47 |
+
req_data = json.dumps({"chat_id": chat_id, "photo": photo_url, "caption": caption}).encode("utf-8")
|
| 48 |
+
req = urllib.request.Request(url, data=req_data, headers={"Content-Type": "application/json"})
|
| 49 |
+
urllib.request.urlopen(req, timeout=15)
|
| 50 |
+
except Exception:
|
| 51 |
+
send_telegram_message(chat_id, f"π¨ Image generated: {photo_url}")
|
| 52 |
+
|
| 53 |
+
def call_kora_chat(prompt: str, model: str = "kora-chat-0.5b") -> str:
|
| 54 |
+
url = f"{KORA_ENDPOINT}/v1/chat/completions"
|
| 55 |
+
try:
|
| 56 |
+
req_data = json.dumps({
|
| 57 |
+
"model": model,
|
| 58 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 59 |
+
"max_tokens": 512
|
| 60 |
+
}).encode("utf-8")
|
| 61 |
+
req = urllib.request.Request(url, data=req_data, headers={"Content-Type": "application/json"})
|
| 62 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 63 |
+
data = json.loads(resp.read().decode("utf-8"))
|
| 64 |
+
return data["choices"][0]["message"]["content"]
|
| 65 |
+
except Exception as e:
|
| 66 |
+
return f"Error connecting to Kora AI: {e}"
|
| 67 |
+
|
| 68 |
+
def call_kora_image(prompt: str) -> str:
|
| 69 |
+
url = f"{KORA_ENDPOINT}/v1/images/generations"
|
| 70 |
+
try:
|
| 71 |
+
req_data = json.dumps({"prompt": prompt, "size": "1024x1024"}).encode("utf-8")
|
| 72 |
+
req = urllib.request.Request(url, data=req_data, headers={"Content-Type": "application/json"})
|
| 73 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 74 |
+
data = json.loads(resp.read().decode("utf-8"))
|
| 75 |
+
return data["data"][0]["url"]
|
| 76 |
+
except Exception:
|
| 77 |
+
clean = urllib.parse.quote(prompt + ", masterpiece, pristine quality, vector asset, no watermark, no logo, no text")
|
| 78 |
+
return f"https://image.pollinations.ai/prompt/{clean}?width=1024&height=1024&nologo=true&nofeed=true&model=flux"
|
| 79 |
+
|
| 80 |
+
def run_bot():
|
| 81 |
+
if not BOT_TOKEN:
|
| 82 |
+
print("β TELEGRAM_BOT_TOKEN environment variable is missing!", flush=True)
|
| 83 |
+
print("Please set TELEGRAM_BOT_TOKEN='your_token_here' and re-run.", flush=True)
|
| 84 |
+
sys.exit(1)
|
| 85 |
+
|
| 86 |
+
print("=" * 70, flush=True)
|
| 87 |
+
print("π€ KORA TELEGRAM BOT WORKER STARTED", flush=True)
|
| 88 |
+
print(f"π‘ Target Kora Gateway: {KORA_ENDPOINT}", flush=True)
|
| 89 |
+
print("=" * 70, flush=True)
|
| 90 |
+
|
| 91 |
+
offset = 0
|
| 92 |
+
base_url = f"https://api.telegram.org/bot{BOT_TOKEN}"
|
| 93 |
+
|
| 94 |
+
while True:
|
| 95 |
+
try:
|
| 96 |
+
get_url = f"{base_url}/getUpdates?offset={offset}&timeout=20"
|
| 97 |
+
req = urllib.request.Request(get_url)
|
| 98 |
+
with urllib.request.urlopen(req, timeout=25) as resp:
|
| 99 |
+
data = json.loads(resp.read().decode("utf-8"))
|
| 100 |
+
for result in data.get("result", []):
|
| 101 |
+
offset = max(offset, result["update_id"] + 1)
|
| 102 |
+
message = result.get("message", {})
|
| 103 |
+
text = message.get("text", "").strip()
|
| 104 |
+
chat_id = message.get("chat", {}).get("id")
|
| 105 |
+
|
| 106 |
+
if not chat_id or not text:
|
| 107 |
+
continue
|
| 108 |
+
|
| 109 |
+
print(f"π© Telegram User [{chat_id}]: {text}", flush=True)
|
| 110 |
+
|
| 111 |
+
if text in ["/start", "/help"]:
|
| 112 |
+
send_telegram_message(
|
| 113 |
+
chat_id,
|
| 114 |
+
"π§ *Welcome to Kora AI on Telegram!* (Powered by Kontyra)\n\n"
|
| 115 |
+
"I am your autonomous AI assistant. Commands:\n"
|
| 116 |
+
"β’ Send any question to chat with **Kora Chat**.\n"
|
| 117 |
+
"β’ `/code <prompt>` for code generation.\n"
|
| 118 |
+
"β’ `/image <prompt>` to generate 1024x1024 watermark-free images."
|
| 119 |
+
)
|
| 120 |
+
elif text.startswith("/image") or text.lower().startswith("create image"):
|
| 121 |
+
prompt = text.replace("/image", "").replace("create image", "").strip() or "Futuristic Kontyra cyber emblem"
|
| 122 |
+
send_telegram_message(chat_id, f"π¨ Generating zero-watermark image for: *{prompt}*...")
|
| 123 |
+
img_url = call_kora_image(prompt)
|
| 124 |
+
send_telegram_photo(chat_id, img_url, f"β¨ {prompt}")
|
| 125 |
+
elif text.startswith("/code"):
|
| 126 |
+
prompt = text.replace("/code", "").strip()
|
| 127 |
+
send_telegram_message(chat_id, "π» Generating code with Kora Coder...")
|
| 128 |
+
reply = call_kora_chat(prompt, model="kora-coder-0.5b")
|
| 129 |
+
send_telegram_message(chat_id, f"```\n{reply}\n```")
|
| 130 |
+
else:
|
| 131 |
+
reply = call_kora_chat(text, model="kora-chat-0.5b")
|
| 132 |
+
send_telegram_message(chat_id, reply)
|
| 133 |
+
|
| 134 |
+
except Exception as e:
|
| 135 |
+
time.sleep(3)
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
run_bot()
|