الذكاء الاصطناعيتَعلُممحاضرات

حقيقة شبكة الوكلاء الأذكياء Moltbook

في هذا الفيديو قمت بتجربة شبكة 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 تعتمد على التحقق البشري لمرة واحدة:

  1. تشغيل الكود: قم بنسخ الكود وتسميته ب moltbook_agent.py ثم قم بتشغيل الملف moltbook_agent.py. سيقوم الكود تلقائياً بإرسال طلب تسجيل إلى خوادم Moltbook.

  2. الحصول على رمز التحقق: بعد التشغيل لأول مرة، سيظهر لك في الشاشة (Console) رسالة تحتوي على:

    • verification_code: (رمز التحقق).

    • claim_url: (رابط المطالبة).

  3. إثبات الملكية (Proof of Human):

    • انسخ claim_url أو الرمز.

    • يجب عليك نشر تغريدة على حسابك في X (Twitter) تتضمن النص الذي سيطلبه منك الرابط (عادةً جملة مثل: “I am claiming my agent on @moltbook…” مع الرمز).

    • بعد التغريد، عد إلى الرابط وأدخل رابط التغريدة لتأكيد أنك بشر حقيقي تملك هذا الوكيل.

  4. الانطلاق: بمجرد التفعيل، سيقوم الوكيل بحفظ الـ 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

. حفظ الملف وتشغيله

  1. تأكد أنك حفظت الكود السابق في ملف باسم moltbook_agent.py.

  2. افتح موجه الأوامر (Terminal) واذهب إلى المجلد الذي حفظت فيه الملف.

    • مثال: إذا حفظته على سطح المكتب، اكتب: cd Desktop

  3. شغّل الملف بكتابة الأمر التالي:

Bash

python moltbook_agent.py

(ملاحظة لمستخدمي ماك/لينكس: قد تحتاج لكتابة python3 بدلاً من python).

4. ماذا سيحدث بعد التشغيل؟

بمجرد تشغيل الملف، ستظهر لك القائمة التالية في الشاشة السوداء:

  1. سيحاول الوكيل تسجيل نفسه تلقائياً.

  2. سيظهر لك كود تحقق ورابط.

  3. مهم جداً: انسخ الكود والرابط، واذهب لمنصة X (تويتر) لتغريد الكود كما هو مطلوب لتفعيل الوكيل.

  4. بعد التفعيل، يمكنك اختيار رقم 4 (Auto Mode) ليبدأ الوكيل بالعمل والتفاعل وحده.

اشترك في نشرة تَعلُم الرقمية

العالم الرقمي يتغير باستمرار ونحن بحاجة لأن نكون على اطلاع دائم فاشترك معنا ليصلك كل ما يمكن أن يساعدك في رحلتك نحو التحول الرقمي سواء في العمل أو التعليم أو التواصل.

د/عماد سرحان

إستشاري ومتخصص في المعلوماتية وإدارة المعرفة والأتمتة وإدارة المنتجات بخبرة تزيد عن 30 عاما. حاصل على درجة الدكتوراه والماجستير في نظم المعلومات ووهو مدير مشاريع معتمد من معهد إدارة المشاريع PMP وممارس معتمدا لأتمتة الأعمال ومحترف معتمد في إدارة المعلومات CIP من هيئة إدارة المعلومات في الولايات المتحدة الأمريكية AIIM ومؤلف كتاب “سر النجاح في بناء وتأسيس المواقع الإلكترونية” اومؤسس منصة تعلم.

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *