مقالات

نحوه استخراج پست های رسانه های اجتماعی برای همه کاربران خود با API


آیا به دنبال این هستید که تمام نشریات رسانه های اجتماعی خود را با کمک API برنامه ریزی کنید؟ این راهنما نحوه استفاده از نقاط پایانی API Ayrshare را برای بازیابی پست های خود در چندین سیستم عامل اجتماعی برای همه پروفایل های خود توضیح می دهد.

برای مشاغل دارای حساب های متعدد در رسانه های اجتماعی ، وجود تجزیه و تحلیل کامل رسانه های اجتماعی یک نیاز استراتژیک است. امکان بازیابی و تجزیه و تحلیل نشریات در کلیه پروفایل های کاربر اطلاعات ارزشمندی را فراهم می کند که می تواند استراتژی رسانه های اجتماعی شما را شکل دهد. این که آیا شما یک آژانس یک آژانس دارید ، مکان های حق رای دادن را مدیریت کنید ، یا تجارت جاه طلبانه لیموناد خود را رشد دهید ، تسلط بر نشریات بی شماری گامی مهم در درک موفقیت شما است.

در این راهنما ، ما نحوه استفاده از Ayrshare API را برای بازیابی مؤثر انتشارات در تمام پروفایل های شما انجام خواهیم داد و در پایان شروع به دیدن چگونگی تبدیل این داده ها به بینش خواهیم کرد. همچنین می توانید اسناد ما را در مورد نحوه دریافت همه پست ها مشاهده کنید.

درک ساختار API

قبل از اینکه خود را در کد غوطه ور کنید ، بیایید یک مرور سریع درباره نحوه عملکرد سلسله مراتب پروفایل Ayrshare بیان کنیم:

  1. حساب اصلی شما (حساب کاربری) به تمام پروفایل های شما دسترسی دارد.
  2. انتهای نقطه /پروفایل داور منحصر به فرد برای هر پروفایل را برمی گرداند.
  3. شما باید نقشه برداری داور خود را به کلیدهای API پروفایل در یک پایگاه داده حفظ کنید.
  4. برای دریافت پست های وی ، کلید مشخصات پروفایل لازم است ،
  5. جریان مانند این کار خواهد کرد:
    • کل نمایه را دریافت کنید refIds از iirshare.
    • به دنبال هر تطبیق باشید Profile-Key در پایگاه داده خود
    • برای بازیابی انتشارات برای هر نمایه در دو نقطه پایانی مختلف از این کلیدهای حساب استفاده کنید.

راهنمای اعدام

تا زمانی که برای این درس از node.js استفاده کنیم ، مفاهیم و ساختار اصلی فراخوان API در تمام زبانهای برنامه نویسی سازگار هستند. بیایید قبل از غوطه ور شدن در یک تفکیک دقیق و مرحله ای ، که به شما در درک عملکرد و هدف هر مؤلفه کمک می کند ، به بررسی کامل کد بپردازیم.

رمز کامل

import 'dotenv/config';

class AyrshareClient {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseURL = 'https://app.ayrshare.com/api';
        this.defaultHeaders = {
            'Authorization': `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json'
        };
    }

    async makeRequest(endpoint, { method = 'GET', headers = {}, params = {}, path = {}, ...options } = {}) {
        // Replace path parameters in endpoint
        let urlEndpoint = endpoint;
        for (const [key, value] of Object.entries(path)) {
            urlEndpoint = urlEndpoint.replace(`:${key}`, value);
        }
        
        let url = `${this.baseURL}${urlEndpoint}`;

        // Add query parameters to URL if they exist
        const queryParams = new URLSearchParams(params).toString();
        if (queryParams) {
            url = `${url}?${queryParams}`;
        }

        const response = await fetch(url, {
            method,
            headers: {
                ...this.defaultHeaders,
                ...headers
            },
            ...options
        });

        if (!response.ok) {
            throw new Error(`API request failed: ${response.status} ${response.statusText}`);
        }

        return response.json();
    }

    async getAllUserProfiles() {
        try {
            const data = await this.makeRequest('/profiles', { method: 'GET' });
            return data.profiles;
        } catch (error) {
            console.error('Error fetching profiles:', error.message);
            throw error;
        }
    }

    async getPostsForProfile(profileKey) {
        try {
            const data = await this.makeRequest('/history', {
                method: 'GET',
                headers: {
                    'Profile-Key': profileKey
                },
                params: {
                    // Example of how to add query parameters if needed
                    // lastRecords: 10,
                    // platforms: ['twitter', 'facebook'].join(',')
                }
            });
            return data.history;
        } catch (error) {
            console.error(`Error fetching posts for profile: ${profileKey}`, error.message);
            throw error;
        }
    }

    async getAllPosts(profileKeyMap) {
        const profiles = await this.getAllUserProfiles();
        const allPosts = [];

        for (const profile of profiles) {
            // Look up the profile key using the refId
            const profileKey = profileKeyMap[profile.refId];
            
            if (!profileKey) {
                console.warn(`No profile key found for refId: ${profile.refId}`);
                continue;
            }

            const posts = await this.getPostsForProfile(profileKey);
            allPosts.push({
                refId: profile.refId,
                posts: posts
            });
        }

        return allPosts;
    }

    async getPostsForPlatform(platform, profileKey) {
        try {
            const data = await this.makeRequest('/history/:platform', {
                method: 'GET',
                headers: {
                    'Profile-Key': profileKey
                },
                path: {
                    platform: platform
                }
            });
            return data.posts;
        } catch (error) {
            console.error(`Error fetching posts for platform: ${platform}`, error.message);
            throw error;
        }
    }

    async getAllPostsForPlatform(platform, profileKeyMap) {
        const profiles = await this.getAllUserProfiles();
        const allPosts = [];

        for (const profile of profiles) {
            const profileKey = profileKeyMap[profile.refId];
            const posts = await this.getPostsForPlatform(platform, profileKey);
            allPosts.push({
                refId: profile.refId,
                posts: posts
            });
        }

        return allPosts;
    }
}

// Usage Example
async function fetchSocialMediaPosts() {
    const client = new AyrshareClient(process.env.AYRSHARE_API_KEY);

    // This would typically come from your internal database
    const profileKeyMap = {
        'ref123': 'profile_key_123',
        'ref456': 'profile_key_456'
        // ... more mappings
    };

    try {
        const allPosts = await client.getAllPosts(profileKeyMap);

        console.log('Successfully retrieved posts for profiles:', 
            allPosts.map(profile => ({
                refId: profile.refId,
                postCount: profile.posts.length
            }))
        );

        const allPostsForPlatform = await client.getAllPostsForPlatform('bluesky', profileKeyMap);

        console.log('Successfully retrieved posts for platform:', 
            allPostsForPlatform.map(profile => ({
                refId: profile.refId,
                postCount: profile.posts.length
            }))
        );


        return allPosts;
    } catch (error) {
        console.error('Failed to fetch posts:', error);
        throw error;
    }
}

fetchSocialMediaPosts();

تجزیه کد

برای اجرای ایمن API ، ما از فرآیند Node.js برای دسترسی به متغیرهای محیطی استفاده خواهیم کرد. حال بیایید هر یک از روشهای موجود در کلاس Ayrshareclient را مطالعه کنیم.


    constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseURL = 'https://app.ayrshare.com/api';
        this.defaultHeaders = {
            'Authorization': `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json'
        };
    }

سازنده داده های احراز هویت را که در درخواست های API زیر به Ayrshare استفاده می شود ، آغاز می کند.


    async makeRequest(endpoint, { method = 'GET', headers = {}, params = {}, path = {}, ...options } = {}) {
        // Replace path parameters in endpoint
        let urlEndpoint = endpoint;
        for (const [key, value] of Object.entries(path)) {
            urlEndpoint = urlEndpoint.replace(`:${key}`, value);
        }
        
        let url = `${this.baseURL}${urlEndpoint}`;

        // Add query parameters to URL if they exist
        const queryParams = new URLSearchParams(params).toString();
        if (queryParams) {
            url = `${url}?${queryParams}`;
        }

        const response = await fetch(url, {
            method,
            headers: {
                ...this.defaultHeaders,
                ...headers
            },
            ...options
        });

        if (!response.ok) {
            throw new Error(`API request failed: ${response.status} ${response.statusText}`);
        }

        return response.json();
    }

مال ما makeRequest این روش به عنوان یک غلاف برای همه تعامل API Ayrshare عمل می کند. در حالی که به طور پیش فرض به GET درخواست ها ، این تبدیل از چندین روش HTTP پشتیبانی می کند و شامل پشتیبانی کامل از پارامترهای جاده ای و درخواست است. در تظاهرات امروز ، همانطور که تمام درخواست های ما خواهد بود GET درخواست ها ، ما به طور خاص روی استفاده از پارامترهای جاده تمرکز خواهیم کرد.


    async getAllUserProfiles() {
        try {
            const data = await this.makeRequest('/profiles', { method: 'GET' });
            return data.profiles;
        } catch (error) {
            console.error('Error fetching profiles:', error.message);
            throw error;
        }
    }

ما با ایجاد روشی برای دریافت کلیه پروفایل های کاربر (/پروفایل) مربوط به مشخصات اصلی شروع می کنیم. از آنجا که داده های شناسایی نمایه اصلی در حال حاضر در سازنده تنظیم شده است ، این روش کاملاً سبک است. توجه داشته باشید که این روش فقط داور مربوط به هر نمایه را برمی گرداند. اطلاعات بیشتر در مورد نحوه دریافت کلید مشخصات کاربر مناسب بعداً.


    async getPostsForProfile(profileKey) {
        try {
            const data = await this.makeRequest('/history', {
                method: 'GET',
                headers: {
                    'Profile-Key': profileKey
                },
                params: {
                    // Example of how to add query parameters if needed
                    // lastRecords: 10,
                    // platforms: ['twitter', 'facebook'].join(',')
                }
            });
            return data.history;
        } catch (error) {
            console.error(`Error fetching posts for profile: ${profileKey}`, error.message);
            throw error;
        }
    }

سپس ما روشی داریم که کلیه انتشارات مربوط به یک کلید پروفایل را دریافت می کند. ما این فراخوان را به این /تاریخ تاریخ انجام می دهیم.


    async getAllPosts(profileKeyMap) {
        const profiles = await this.getAllUserProfiles();
        const allPosts = [];

        for (const profile of profiles) {
            // Look up the profile key using the refId
            const profileKey = profileKeyMap[profile.refId];
            
            if (!profileKey) {
                console.warn(`No profile key found for refId: ${profile.refId}`);
                continue;
            }

            const posts = await this.getPostsForProfile(profileKey);
            allPosts.push({
                refId: profile.refId,
                posts: posts
            });
        }

        return allPosts;
    }

این روش بعدی AyrshareClient کلاس به هم متصل می شود getAllUserProfiles() getPostsForProfile(profileKey) روشها ما معرفی می کنیم profileKeyMap این شناسه های مرجع (داوران) را به کلیدهای حساب مربوطه از پایگاه داده داخلی خود متصل می کند. این روش مجموعه ای از کلیه نشریات مربوط به بازپرداخت هر نمایه را برمی گرداند.


    async getPostsForPlatform(platform, profileKey) {
        try {
            const data = await this.makeRequest('/history/:platform', {
                method: 'GET',
                headers: {
                    'Profile-Key': profileKey
                },
                path: {
                    platform: platform
                }
            });
            return data.posts;
        } catch (error) {
            console.error(`Error fetching posts for platform: ${platform}`, error.message);
            throw error;
        }
    }

در اینجا ما روشی برای ضربه زدن به نقطه پایان /::: سکو داریم. با توجه به کلید پلتفرم و مشخصات پروفایل ، انتشارات را از این پلتفرم باز می گرداند (هم از طریق Ayrshare و هم از طریق ایجاد شده در افراد محلی روی خود سیستم عامل).


    async getAllPostsForPlatform(platform, profileKeyMap) {
        const profiles = await this.getAllUserProfiles();
        const allPosts = [];

        for (const profile of profiles) {
            const profileKey = profileKeyMap[profile.refId];

            if (!profileKey) {
                console.warn(`No profile key found for refId: ${profile.refId}`);
                continue;
            }

            const posts = await this.getPostsForPlatform(platform, profileKey);
            allPosts.push({
                refId: profile.refId,
                posts: posts
            });
        }

        return allPosts;
    }

و آخرین روش ما این است که تمام نشریات یک بستر خاص را از پروفایل های کاربر مربوط به حساب اصلی ما بدست آوریم. این اکنون ترکیبی از استفاده است getAllUserProfiles وت getPostsForPlatform روشها این یک بار دیگر از یک پروفایل داخلی پروفایل استفاده می کند و یک آرایه را از هر داور به همراه پست های خاص پلت فرم مناسب خود باز می گرداند.


// Usage Example
async function fetchSocialMediaPosts() {
    const client = new AyrshareClient(process.env.AYRSHARE_API_KEY);

    // This would typically come from your internal database
    const profileKeyMap = {
        'ref123': 'profile_key_123',
        'ref456': 'profile_key_456'
        // ... more mappings
    };

    try {
        const allPosts = await client.getAllPosts(profileKeyMap);

        console.log('Successfully retrieved posts for profiles:', 
            allPosts.map(profile => ({
                refId: profile.refId,
                postCount: profile.posts.length
            }))
        );

        const allPostsForPlatform = await client.getAllPostsForPlatform('bluesky', profileKeyMap);

        console.log('Successfully retrieved posts for platform:', 
            allPostsForPlatform.map(profile => ({
                refId: profile.refId,
                postCount: profile.posts.length
            }))
        );


        return [allPosts, allPostsForPlatform];
    } catch (error) {
        console.error('Failed to fetch posts:', error);
        throw error;
    }
}

fetchSocialMediaPosts();

سرانجام ، در اینجا دو نمونه استفاده در بازی آورده شده است. بعد از تنظیم AyrshareClient کپی و عرضه profileKeyMap از فروشگاه داخلی خود ما تماس می گیریم getAllPostsاز آنجا می توانید نقشه برداری را مشاهده کنید که تعداد انتشارات مربوط به هر داور را حساب می کنیم. نظارت getAllPostsForPlatform به bluesky وت profileKeyMapS شما نقشه برداری هر داور را دوباره با تعداد مربوط به نشریات خود مشاهده خواهید کرد.


بهترین شیوه ها و ملاحظات

امنیت اصلی API

  • هرگز کلیدهای کنترل کلید API را درگیر نکنید (بله ، من به نظر می رسد repos github عمومی).
  • از متغیرهای محیطی استفاده کنید.
  • کلیدهای امنیتی API را مرتباً بچرخانید. این کار را می توان در داشبورد مدیریت Ayrshare انجام داد.

خطاها

  • خطاهای کاملاً پردازش.
  • خطاهای ثبت نام مناسب.
  • در نظر بگیرید که برای درخواست های ناموفق ، re -logic را در نظر بگیرید.

سرعت

  • به خاطر داشته باشید محدودیت سرعت API Ayrshare.
  • تأخیرهای مناسب را بین درخواست ها اعمال کنید.
  • استفاده از یک سیستم صف را برای مجموعه داده های بزرگ در نظر بگیرید (مثال: تعداد زیادی پروفایل کاربر دارید).

این تبدیل مبنای کاملی برای استخراج نشریات در تمام پروفایل های شما فراهم می کند. ما آن را به اندازه کافی مدولار نگه داشتیم تا بتوانید به راحتی در بالا بسازید و کد خود را حفظ کنید. تبریک می گویم!


Source link

نوشته های مشابه

دیدگاهتان را بنویسید

دکمه بازگشت به بالا