Let's build a telegram AI bot with all the functions @sumatman_bot has, there are only three major code blocks you need.
- Flask for webhook
@app.route('/telegram', methods=['POST'])
def telegram_webhook():
"""Handle incoming Telegram messages."""
try:
# Parse the incoming update
update = request.json
if not update: return jsonify({"status": "ignored", "message": "No valid update found"})
thread = Thread(target=process_telegram_message, args=(update,))
thread.start()
return jsonify({"status": "success"})
except Exception as e: return jsonify({"status": "error", "message": str(e)})
- Call sumatman's endpoint
def call_function_endpoint(prompt, api_key=SUMATMAN_API_KEY, base_url=PUBLIC_API_URL):
"""
Calls the /v1/function endpoint with the given prompt and API key.
:param prompt: The user's message to be processed
:param api_key: The API key for authorization
:param base_url: The base URL of the API (default is PUBLIC_API_URL)
:return: The response as a JSON object
"""
endpoint = f"{base_url}/v1/function"
headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}
payload = {"prompt": prompt}
try:
response = requests.post(endpoint, headers=headers, json=payload)
print(f"Response Status Code: {response.status_code}")
return response.json()
except ValueError as ve: return {"status": "error", "message": "Invalid JSON response", "details": response.text}
except Exception as e: return {"status": "error", "message": str(e)}
- Telegram message process
def process_telegram_message(update):
"""Process a Telegram message in a separate thread."""
update_message = update["message"]
chat_id = update_message["chat"]["id"]
chat_id = str(chat_id)
message_text = update_message.get("text", "")
api_key = SUMATMAN_API_KEY
if message_text:
message_id = send_message_markdown(chat_id, f"Processing ...", telegram_token)
ai_response = call_function_endpoint(message_text, api_key, base_url=PUBLIC_API_URL)
# Handle response based on content type
if ai_response["status"] == "success":
content_type = ai_response["data"].get("content_type")
content = ai_response["data"].get("content")
content = content.get('content_string', 'No response') if content_type in ["crypto/ticker", "stock/ticker", "crypto/balance"] else content
if content_type == "audio/mpeg": send_audio_url(chat_id, content, telegram_token, '', message_id)
elif content_type == "image/jpeg": send_image_url(chat_id, content, telegram_token, '', message_id)
send_message_markdown(chat_id, content, telegram_token, message_id)
else: send_message_markdown(chat_id, ai_response.get("message"), telegram_token, message_id)
Variables:
- PUBLIC_API_URL = https://api.sumatman.ai
- SUMATMAN_API_KEY = Your API Key (get it from @sumatman_bot)