Team Ai
Apppublic

azils3/bash

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
twitter.py206 linesDownload Raw Back to plugins
1# Ultroid - UserBot2# Copyright (C) 2021-2025 TeamUltroid3#4# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >5# PLease read the GNU Affero General Public License in6# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.7 8"""9✘ Commands Available -10 11• `{i}tw <tweet text>`12    Tweet the text.13 14• `{i}twr <tweet id/link>`15    Get tweet details with reply/quote/comment count.16 17• `{i}twuser <username>`18    Get user details of the Twitter account.19 20• `{i}twl <tweet link>`21    Upload the tweet media to telegram.22 23"""24 25import os26from twikit import Client27from . import LOGS, eor, get_string, udB, ultroid_cmd28 29# Store client globally30twitter_client = None31 32# Get path to cookies file33COOKIES_FILE = "resources/auth/twitter_cookies.json"34 35async def get_client():36    global twitter_client37    if twitter_client:38        return twitter_client39        40    if not all(udB.get_key(key) for key in ["TWITTER_USERNAME", "TWITTER_EMAIL", "TWITTER_PASSWORD"]):41        raise Exception("Set TWITTER_USERNAME, TWITTER_EMAIL and TWITTER_PASSWORD in vars first!")42    43    # Create auth directory if it doesn't exist44    os.makedirs(os.path.dirname(COOKIES_FILE), exist_ok=True)45        46    client = Client()47    await client.login(48        auth_info_1=udB.get_key("TWITTER_USERNAME"),49        auth_info_2=udB.get_key("TWITTER_EMAIL"), 50        password=udB.get_key("TWITTER_PASSWORD"),51        cookies_file=COOKIES_FILE52    )53    twitter_client = client54    return client55 56 57 58@ultroid_cmd(pattern="tw( (.*)|$)")59async def tweet_cmd(event):60    """Post a tweet"""61    text = event.pattern_match.group(1).strip()62    if not text:63        return await event.eor("🚫 `Give some text to tweet!`")64 65    msg = await event.eor("🕊 `Tweeting...`")66    try:67        client = await get_client()68        tweet = await client.create_tweet(text=text)69        await msg.edit(f"✨ **Successfully Posted!**\n\n🔗 https://x.com/{tweet.user.screen_name}/status/{tweet.id}")70    except Exception as e:71        await msg.edit(f"❌ **Error:**\n`{str(e)}`")72 73 74@ultroid_cmd(pattern="twdetail( (.*)|$)")75async def twitter_details(event):76    """Get tweet details"""77    match = event.pattern_match.group(1).strip()78    if not match:79        return await event.eor("🚫 `Give tweet ID/link to get details!`")80 81    msg = await event.eor("🔍 `Getting tweet details...`")82    try:83        client = await get_client()84        from urllib.parse import urlparse85        parsed_url = urlparse(match)86        if parsed_url.hostname in ["twitter.com", "x.com"]:87            tweet_id = parsed_url.path.split("/")[-1].split("?")[0]88        else:89            tweet_id = match90 91        tweet = await client.get_tweet_by_id(tweet_id)92        text = "🐦 **Tweet Details**\n\n"93        text += f"📝 **Content:** `{tweet.text}`\n\n"94        if hasattr(tweet, "metrics"):95            text += f"❤️ **Likes:** `{tweet.metrics.likes}`\n"96            text += f"🔄 **Retweets:** `{tweet.metrics.retweets}`\n"97            text += f"💬 **Replies:** `{tweet.metrics.replies}`\n"98            text += f"👁 **Views:** `{tweet.metrics.views}`\n"99        100        await msg.edit(text)101    except Exception as e:102        await msg.edit(f"❌ **Error:**\n`{str(e)}`")103 104 105@ultroid_cmd(pattern="twuser( (.*)|$)")106async def twitter_user(event):107    """Get user details"""108    match = event.pattern_match.group(1).strip()109    if not match:110        return await event.eor("🚫 `Give username to get details!`")111 112    msg = await event.eor("🔍 `Getting user details...`")113    try:114        client = await get_client()115        user = await client.get_user_by_screen_name(match)116        text = "👤 **Twitter User Details**\n\n"117        text += f"📛 **Name:** `{user.name}`\n"118        text += f"🔖 **Username:** `@{user.screen_name}`\n"119        text += f"📝 **Bio:** `{user.description}`\n\n"120        text += f"👥 **Followers:** `{user.followers_count}`\n"121        text += f"👣 **Following:** `{user.following_count}`\n"122        text += f"🐦 **Total Tweets:** `{user.statuses_count}`\n"123        text += f"📍 **Location:** `{user.location or 'Not Set'}`\n"124        text += f"✅ **Verified:** `{user.verified}`\n"125        126        if user.profile_image_url:127            image_url = user.profile_image_url.replace("_normal.", ".")128            await event.client.send_file(129                event.chat_id,130                file=image_url,131                caption=text,132                force_document=False133            )134            await msg.delete()135        else:136            await msg.edit(text)137            138    except Exception as e:139        await msg.edit(f"❌ **Error:**\n`{str(e)}`")140 141 142@ultroid_cmd(pattern="twl( (.*)|$)")143async def twitter_media(event):144    """Download tweet media"""145    match = event.pattern_match.group(1).strip()146    if not match:147        return await event.eor("🚫 `Give tweet link to download media!`")148 149    msg = await event.eor("📥 `Downloading media...`")150    try:151        client = await get_client()152        if "twitter.com" in match or "x.com" in match:153            tweet_id = match.split("/")[-1].split("?")[0]154        else:155            tweet_id = match156 157        tweet = await client.get_tweet_by_id(tweet_id)158        159        if not hasattr(tweet, "media"):160            return await msg.edit("😕 `No media found in tweet!`")161 162        # Prepare caption with tweet text163        caption = f"🐦 **Tweet by @{tweet.user.screen_name}**\n\n"164        caption += f"{tweet.text}\n\n"165        if hasattr(tweet, "metrics"):166            caption += f"❤️ `{tweet.metrics.likes}` 🔄 `{tweet.metrics.retweets}` 💬 `{tweet.metrics.replies}`"167 168        media_count = 0169        for media in tweet.media:170            if media.type == "photo":171                await event.client.send_file(172                    event.chat_id, 173                    media.url,174                    caption=caption if media_count == 0 else None  # Only add caption to first media175                )176                media_count += 1177            elif media.type == "video":178                if hasattr(media, "video_info") and isinstance(media.video_info, dict):179                    variants = media.video_info.get("variants", [])180                    mp4_variants = [181                        v for v in variants 182                        if v.get("content_type") == "video/mp4" and "bitrate" in v183                    ]184                    if mp4_variants:185                        best_video = max(mp4_variants, key=lambda x: x["bitrate"])186                        video_caption = caption if media_count == 0 else ""  # Only add tweet text to first media187                        if video_caption:188                            video_caption += f"\n🎥 Video Quality: {best_video['bitrate']/1000:.0f}kbps"189                        else:190                            video_caption = f"🎥 Video Quality: {best_video['bitrate']/1000:.0f}kbps"191                            192                        await event.client.send_file(193                            event.chat_id,194                            best_video["url"],195                            caption=video_caption196                        )197                        media_count += 1198 199        if media_count > 0:200            await msg.edit(f"✅ Successfully downloaded {media_count} media items!")201            await msg.delete()202        else:203            await msg.edit("😕 `No media could be downloaded!`")204    except Exception as e:205        await msg.edit(f"❌ **Error:**\n`{str(e)}`")206