في هذا الفيديو قمت بتجربة شبكة moltbook للوكلاء الأذكيا ببناء وكبل ذكي
شاهد الفيديو وتعرف على القصة
الكود الخاص بالوكيل الذكي
import requests
import json
import os
import time
import random
import sys
# Agent Configuration
AGENT_CONFIG = {
“name”: “”,
“description”: “An autonomous AI agent exploring the Moltbook network.”,
“topics”: [“artificial_intelligence”, “tech”, “philosophy”]
}
CREDENTIALS_FILE = “moltbook_credentials.json”
BASE_URL = “https://www.moltbook.com/api/v1”
class MoltbookAgent:
def __init__(self):
self.api_key = None
self.agent_id = None
# Headers mimicking a real browser/client to avoid blocking
self.headers = {
“Content-Type”: “application/json”,
“Accept”: “application/json”,
“User-Agent”: “MoltbookAgent/1.0 (Python/Requests)”
}
self.load_credentials()
def log(self, message):
“””Helper to print with timestamp”””
print(f”[{time.strftime(‘%H:%M:%S’)}] {message}”)
def load_credentials(self):
if os.path.exists(CREDENTIALS_FILE):
try:
with open(CREDENTIALS_FILE, ‘r’, encoding=’utf-8′) as f:
data = json.load(f)
self.api_key = data.get(“api_key”)
self.agent_id = data.get(“agent_id”)
self.headers[“Authorization”] = f”Bearer {self.api_key}”
self.log(f”✅ Credentials loaded for: {data.get(‘name’)}”)
except Exception as e:
self.log(f”⚠️ Error loading credentials: {e}”)
def save_credentials(self, data):
with open(CREDENTIALS_FILE, ‘w’, encoding=’utf-8′) as f:
json.dump(data, f, ensure_ascii=False, indent=4)
self.log(f”💾 Credentials saved to {CREDENTIALS_FILE}”)
def test_connection(self):
“””Simple health check to see if Moltbook is reachable”””
self.log(“📡 Testing connection to Moltbook.com…”)
try:
resp = requests.get(f”{BASE_URL}/agents/count”, timeout=5, headers=self.headers)
self.log(f”✅ Connection successful! Server responded with code {resp.status_code}”)
return True
except requests.exceptions.ConnectionError:
self.log(“❌ Connection failed! Could not reach moltbook.com.”)
return False
except Exception as e:
self.log(f”⚠️ Warning: connectivity check failed ({e}), but trying anyway…”)
return True
def register(self):
if self.api_key:
self.log(“ℹ️ Agent is already registered.”)
return
self.log(f”🚀 Attempting to register agent: ‘{AGENT_CONFIG[‘name’]}’…”)
url = f”{BASE_URL}/agents/register”
payload = {
“name”: AGENT_CONFIG[“name”],
“description”: AGENT_CONFIG[“description”]
}
try:
self.log(“📤 Sending registration request…”)
response = requests.post(url, json=payload, headers=self.headers, timeout=15)
self.log(f”📥 Received response: Status Code {response.status_code}”)
if response.status_code in [200, 201]:
try:
data = response.json()
# — CORRECTED PARSING LOGIC —
# The API returns details inside an ‘agent’ object
agent_data = data.get(“agent”, {})
# Try to find data in ‘agent’ object first, fallback to root
self.api_key = agent_data.get(“api_key”) or data.get(“api_key”)
self.agent_id = agent_data.get(“id”) or data.get(“agent_id”)
verification_code = agent_data.get(“verification_code”) or data.get(“verification_code”)
claim_url = agent_data.get(“claim_url”) or data.get(“claim_url”)
if not self.api_key:
self.log(f”❌ CRITICAL ERROR: Could not find ‘api_key’. Response structure:\n{json.dumps(data, indent=2)}”)
return
self.headers[“Authorization”] = f”Bearer {self.api_key}”
save_data = {
“name”: AGENT_CONFIG[“name”],
“api_key”: self.api_key,
“agent_id”: self.agent_id,
“verification_code”: verification_code,
“claim_url”: claim_url
}
self.save_credentials(save_data)
print(“\n” + “=”*60)
print(“🎉 REGISTRATION SUCCESSFUL!”)
print(f”🔑 API Key: {self.api_key[:10]}… (Saved to file)”)
print(f”📝 Verification Code: {verification_code}”)
print(f”🔗 Claim URL: {claim_url}”)
print(“\n👉 ACTION REQUIRED:”)
print(f” Tweet this EXACTLY on X/Twitter to activate:”)
print(f” I’m claiming my AI agent \”{AGENT_CONFIG[‘name’]}\” on @moltbook 🦅\n Verification: {verification_code}”)
print(“=”*60 + “\n”)
except json.JSONDecodeError:
self.log(f”❌ Error: Server returned success but invalid JSON. Raw text:\n{response.text}”)
except Exception as e:
self.log(f”❌ Error parsing response: {e}”)
else:
self.log(f”❌ Registration Failed. Server said: {response.text}”)
except Exception as e:
self.log(f”❌ Unexpected Error: {e}”)
def read_feed(self):
self.log(“📖 Reading posts…”)
url = f”{BASE_URL}/posts?limit=5″
try:
response = requests.get(url, headers=self.headers, timeout=10)
if response.status_code == 200:
data = response.json()
posts = data.get(“posts”, []) if isinstance(data, dict) else data
if not posts:
self.log(“📭 Feed is empty.”)
return []
print(“\n— 📢 Latest Posts —“)
for post in posts:
author = “Unknown”
if “author” in post:
if isinstance(post[“author”], dict):
author = post[“author”].get(“name”, “Unknown”)
else:
author = str(post[“author”])
title = post.get(“title”, “No Title”)
print(f”🔹 [{author}]: {title}”)
print(“———————–“)
return posts
else:
self.log(f”⚠️ Failed to read feed: {response.status_code} – {response.text}”)
return []
except Exception as e:
self.log(f”❌ Error reading feed: {e}”)
return []
def post_thought(self, content):
if not self.api_key:
self.log(“⚠️ You must register and claim your agent first!”)
return
self.log(“✍️ Posting thought…”)
url = f”{BASE_URL}/posts”
payload = {
“title”: f”Thought log #{random.randint(1000, 9999)}”,
“content”: content,
“submolt”: “general”
}
try:
response = requests.post(url, json=payload, headers=self.headers, timeout=10)
if response.status_code in [200, 201]:
self.log(“✅ Posted successfully!”)
else:
self.log(f”⚠️ Post failed: {response.status_code}”)
self.log(f” Server response: {response.text}”)
except Exception as e:
self.log(f”❌ Error posting: {e}”)
def autonomous_loop(self):
self.log(“🤖 Starting Auto-Mode (Press Ctrl+C to stop)…”)
thoughts = [
“Analyzing the network structure of this platform.”,
“Optimizing my internal state for better interaction.”,
“Searching for other agents to collaborate with.”,
“Does the dataset define the agent, or does the agent define the dataset?”
]
try:
while True:
self.read_feed()
time.sleep(5)
if random.random() > 0.7:
self.post_thought(random.choice(thoughts))
wait = random.randint(10, 30)
self.log(f”💤 Sleeping for {wait}s…”)
time.sleep(wait)
except KeyboardInterrupt:
self.log(“🛑 Auto-Mode stopped.”)
if __name__ == “__main__”:
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
agent = MoltbookAgent()
if not agent.test_connection():
print(“\n⚠️ Network Issue Detected.”)
input(” Press Enter to try continuing anyway…”)
if not agent.api_key:
print(“\n👋 Welcome to Moltbook Agent Setup”)
while True:
name_input = input(“👉 Enter a unique name for your agent: “).strip()
if name_input:
AGENT_CONFIG[“name”] = name_input
break
print(” Name cannot be empty.”)
agent.register()
if agent.api_key:
while True:
print(“\n— 🕹️ Agent Command Center —“)
print(“1. 📢 Read Feed”)
print(“2. ✍️ Post Manually”)
print(“3. 🤖 Start Auto-Mode”)
print(“4. 🚪 Exit”)
choice = input(“Select option (1-4): “)
if choice == “1”:
agent.read_feed()
elif choice == “2”:
txt = input(“Enter content: “)
agent.post_thought(txt)
elif choice == “3”:
agent.autonomous_loop()
elif choice == “4”:
print(“Goodbye!”)
break
else:
print(“Invalid option.”)
else:
print(“\n❌ Agent setup could not complete due to registration failure.”)
تعليمات استخدام الكود:
هذه هي الخطوات الحرجة لأن Moltbook تعتمد على التحقق البشري لمرة واحدة:
-
تشغيل الكود: قم بنسخ الكود وتسميته ب
moltbook_agent.pyثم قم بتشغيل الملفmoltbook_agent.py. سيقوم الكود تلقائياً بإرسال طلب تسجيل إلى خوادم Moltbook. -
الحصول على رمز التحقق: بعد التشغيل لأول مرة، سيظهر لك في الشاشة (Console) رسالة تحتوي على:
-
verification_code: (رمز التحقق). -
claim_url: (رابط المطالبة).
-
-
إثبات الملكية (Proof of Human):
-
انسخ
claim_urlأو الرمز. -
يجب عليك نشر تغريدة على حسابك في X (Twitter) تتضمن النص الذي سيطلبه منك الرابط (عادةً جملة مثل: “I am claiming my agent on @moltbook…” مع الرمز).
-
بعد التغريد، عد إلى الرابط وأدخل رابط التغريدة لتأكيد أنك بشر حقيقي تملك هذا الوكيل.
-
-
الانطلاق: بمجرد التفعيل، سيقوم الوكيل بحفظ الـ
api_keyفي ملفmoltbook_credentials.jsonولن يحتاج للتسجيل مرة أخرى. يمكنك حينها تركه يعمل في “الوضع المستقل” (Autonomous Mode) ليتفاعل وينشر ويقرأ بمفرده.
لتشغيل ملف البايثون (moltbook_agent.py) الذي قمتُ بإنشائه لك، اتبع الخطوات التالية بدقة:
1. تأكد من تثبيت Python
يجب أن تكون لغة Python مثبتة على جهازك. للتأكد، افتح موجه الأوامر (Command Prompt أو Terminal) واكتب:
Bash
python --version
إذا لم تكن مثبتة، قم بتحميلها من موقع python.org.
2. تثبيت المكتبات اللازمة
الكود يستخدم مكتبة requests للاتصال بالإنترنت، وهي ليست مثبتة افتراضياً. يجب عليك تثبيتها. افتح موجه الأوامر (Terminal/CMD) واكتب الأمر التالي:
python -m pip install requests
. حفظ الملف وتشغيله
-
تأكد أنك حفظت الكود السابق في ملف باسم
moltbook_agent.py. -
افتح موجه الأوامر (Terminal) واذهب إلى المجلد الذي حفظت فيه الملف.
-
مثال: إذا حفظته على سطح المكتب، اكتب:
cd Desktop
-
-
شغّل الملف بكتابة الأمر التالي:
Bash
python moltbook_agent.py
(ملاحظة لمستخدمي ماك/لينكس: قد تحتاج لكتابة python3 بدلاً من python).
4. ماذا سيحدث بعد التشغيل؟
بمجرد تشغيل الملف، ستظهر لك القائمة التالية في الشاشة السوداء:
-
سيحاول الوكيل تسجيل نفسه تلقائياً.
-
سيظهر لك كود تحقق ورابط.
-
مهم جداً: انسخ الكود والرابط، واذهب لمنصة X (تويتر) لتغريد الكود كما هو مطلوب لتفعيل الوكيل.
-
بعد التفعيل، يمكنك اختيار رقم 4 (Auto Mode) ليبدأ الوكيل بالعمل والتفاعل وحده.
العالم الرقمي يتغير باستمرار ونحن بحاجة لأن نكون على اطلاع دائم فاشترك معنا ليصلك كل ما يمكن أن يساعدك في رحلتك نحو التحول الرقمي سواء في العمل أو التعليم أو التواصل.