Telegram-bot-api向指定频道批量上传本地媒体(Local Bot API Server)

Telegram-bot-api向指定频道批量上传本地媒体(Local Bot API Server)

背景

目前直接使用https://api.telegram.org服务上传媒体有文件大小的限制,根据TG官方API文档介绍(https://core.telegram.org/bots/api#using-a-local-bot-api-server),使用本地服务上传文件最大可达 2000 MB
在这里插入图片描述

申请TG机器人(Telegram Bot)

  1. 登录Telegram,搜索@BotFather
  2. 发送命令/newbot,输入bot名称、bot用户名,最后会获得一个HTTP API
    在这里插入图片描述

申请TG Application

  1. 打开https://my.telegram.org
  2. 输入手机号登陆后自行申请
App title: TestApp1
Short name: testapp1
URL: N/A (Fill nothings here)
Platform: Desktop
Description: N/A (Fill nothings here)
  1. 如果申请报错ERROR,请使用与登录手机号地区相同的代理,+86的可以使用HK地区的代理。
  2. 最后获取API-ID以及API-HASH
    在这里插入图片描述

安装Telegram本地API服务

  1. 可参考https://tdlib.github.io/telegram-bot-api/build.html
  2. 下载并安装Microsoft Visual Studio。安装时启用C++支持。
  3. 下载并安装 CMake;安装时选择“Add CMake to the system PATH”选项。
  4. 下载并安装 Git
  5. 依次执行下面的命令
git clone --recursive https://github.com/tdlib/telegram-bot-api.git
cd telegram-bot-api
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.bat
./vcpkg.exe install gperf:x64-windows openssl:x64-windows zlib:x64-windows
cd ..
Remove-Item build -Force -Recurse -ErrorAction SilentlyContinue
mkdir build
cd build
cmake -A x64 -DCMAKE_INSTALL_PREFIX:PATH=.. -DCMAKE_TOOLCHAIN_FILE:FILEPATH=../vcpkg/scripts/buildsystems/vcpkg.cmake ..
cmake --build . --target install --config Release
cd ../..
dir telegram-bot-api/bin/telegram-bot-api*
  1. 进入bin文件夹,启动本地服务器。如果网络不通可以使用Proxifier代理telegram-bot-api.exe
.\telegram-bot-api.exe --api-id=[YOUR API-ID] --api-hash=[YOUR API-HASH] --local

Telegram-bot-api

  1. 首先要把你的bot从官方登出,把url中[BOT HTTP API]替换成你上面在BotFather申请的HTTP API,复制到浏览器,响应返回true,登出成功。
    http://127.0.0.1:8081/bot[BOT HTTP API]/logOut
  2. 添加你的bot到TG频道。可以使用python或者直接用官方文档中的api进行操作,以下是使用python的例子
  3. 获取频道ID
import asyncio
from telegram import Bot

# 替换成你的Bot HTTP API
TOKEN = 'YOU BOT HTTP API'
bot = Bot(token=TOKEN, base_url='http://127.0.0.1:8081/bot', base_file_url='http://127.0.0.1:8081/file/bot')

async def get_updates():
    updates = await bot.get_updates()
    print(updates)
    for update in updates:
        if update.message:
            print(f"Chat ID: {update.message.chat.id}")

async def main():
    await get_updates()

if __name__ == '__main__':
    asyncio.run(main())
  1. 从本地文件夹上传媒体
    需求背景:本地父文件夹中存在多个子文件夹,子文件夹中存在多个图片/视频媒体,要求遍历子文件夹,将相同子文件夹中的媒体合并发送至指定频道,并把子文件夹名称作为发送消息的说明文字
    首先安装依赖
    pip install python-telegram-bot
    
    实现:
    import os
    import asyncio
    from telegram import Bot, InputMediaPhoto, InputMediaVideo
    from telegram.error import NetworkError
    
    # 替换成你的Bot HTTP API
    TOKEN = 'YOUR Bot HTTP API'
    # 替换成你的频道ID,一般是负数
    GROUP_ID = 'YOUR GROUP ID'
    # 媒体所在的父目录
    DIRECTORY = 'YOUR MEDIA DIRECTORY'
    
    bot = Bot(token=TOKEN, base_url='http://127.0.0.1:8081/bot', base_file_url='http://127.0.0.1:8081/file/bot')
    
    
    async def send_media(folder_path, folder_name):
        media_files = []
        for file in os.listdir(folder_path):
            file_path = os.path.join(folder_path, file)
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                media_files.append(InputMediaPhoto(open(file_path, 'rb')))
            elif file.lower().endswith(('.mp4', '.avi', '.mov')):
                media_files.append(InputMediaVideo(open(file_path, 'rb')))
    
        # 分批发送媒体文件
        max_files_per_message = 10
        for i in range(0, len(media_files), max_files_per_message):
            media_group = media_files[i:i + max_files_per_message]
            if media_group:
                try:
                    await bot.send_media_group(chat_id=GROUP_ID, media=media_group, caption=folder_name, read_timeout=1000,
                                               write_timeout=1000,connect_timeout=1000)
                    print(f"{datetime.now()} - Sent {len(media_group)} items from {folder_name}")
                except NetworkError as e:
                    print(f"Failed to send due to {e}")
            await asyncio.sleep(5)  # 避免过快发送
    
    
    async def main():
        root_dir = DIRECTORY
        for folder_name in os.listdir(root_dir):
            folder_path = os.path.join(root_dir, folder_name)
            if os.path.isdir(folder_path):
                await send_media(folder_path, folder_name)
                
    
    if __name__ == "__main__":
        asyncio.run(main())
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值