1.创建telegram bot

首先我们要到telegram上面去搜@BotFather

完整版本创建telegram bot_数据

完整版本创建telegram bot_数据_02

如果username 重复会让你重新选择

创建成功后会返回机器人的token,可以保存好备用,不要泄露自己的token

完整版本创建telegram bot_php_03

2.设计功能

首先,我要做一个影视机器人,用来给用户提供影视资源

功能列表

自动问候

用户发送问候语,机器人随机返回

影视URL解析

使用影视解析api返回解析后的观影链接

影视名称搜索网盘资源

用户发送影视名称,返回网盘链接

3.源码实现

import logging
import random
import requests
from telegram import Update, Bot
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters, CallbackContext

# 打印日志方法
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)

# 定义电影API接口
MOVIE_API_URL = "https://xiaoapi.cn/API/jx_txsp.php"
# 定义电影盘API接口
PAN_API_URL = "https://www.hhlqilongzhu.cn/api/ziyuan_nanfeng.php"


# 调用电影API接口获取电影数据
async def get_movie_data(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 获取用户输入的电影url
    movie_url = update.message.text
    # 发送请求到API接口
    response = requests.get(MOVIE_API_URL, params=movie_url)
    # 检查响应状态码
    if response.status_code == 200:
        movie_info = response.json()  # 假设API返回的是JSON格式数据
        # 检查是否有电影数据返回
        if movie_info and 'title' in movie_info:
            # 发送电影信息给用户
            await update.message.reply_text("解析成功啦!")
            await update.message.reply_text(
                "点击这里访问 [" + movie_info['title'] + "]" + "(" + movie_info['url'] + ")", parse_mode='Markdown')
        else:
            await update.message.reply_text("抱歉,没有找到相关的影片解析信息。")
    else:
        await update.message.reply_text("无法连接到电影API接口。")

# 调用电影网盘资源API接口获取电影数据
async def get_movieName_data(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 获取用户输入的电影名称
    movie_name = update.message.text
    # 发送请求到API接口
    response = requests.get(PAN_API_URL, params={'keysearch': movie_name})
    # 检查响应状态码
    if response.status_code == 200:
        movie_info = response.json()  # 假设API返回的是JSON格式数据
        # 检查是否有电影数据返回
        if 'data' in movie_info:
            await update.message.reply_text("获取资源成功" + "! 共找到" + str(movie_info['count']) + '条资源')
            # 发送电影信息给用户
            num = 0
            mastext = []
            for i in movie_info['data']:
                num += 1
                mastext.append(f"{num}:{i['title']}-({i['data_url']})  ")
            await update.message.reply_text('\n'.join(mastext), parse_mode=None)
        else:
            await update.message.reply_text("抱歉,没有找到相关的影片信息。")
    else:
        await update.message.reply_text("无法连接到PAN_API_URL接口。")


# CommandHandler 一些命令方法
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    '''响应start命令'''
    text = '欢迎使用可搜机器人,您可以发送VIP视频链接给我解析'
    await context.bot.send_message(chat_id=update.effective_chat.id, text=text)


async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
    '''响应help命令'''
    text = "=" * 5 + '开发者信息' + "=" * 5 + "\n" + "Developer:RenYuke"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=text)


async def ohayo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    '''随机消息'''
    texts = ['早上好呀', '我的小鱼你醒了,还记得清晨吗', '哦哈哟~']
    await context.bot.send_message(chat_id=update.effective_chat.id, text=random.choice(texts))

# 判断用户发送的消息是URL还是电影名称去选择对应的处理方法
async def choose_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 检查消息是否为文本消息
    if update.message.text:
        text = update.message.text
        # 检查文本是否以https开头
        if text.startswith('https://'):
            # 是URL,调用处理URL的函数
            await get_movie_data(update, context)
        else:
            # 不是URL,调用处理电影名称的函数
            await get_movieName_data(update, context)


def main():
    # 命令响应
    start_handler = CommandHandler('start', start)
    help_handler = CommandHandler('help', help)
    # 消息匹配
    filter_ohayo = filters.Regex('早安|早上好|哦哈哟|ohayo|早')
    ohayo_handler = MessageHandler(filter_ohayo, ohayo)

    # 添加消息处理器,用于处理用户发送的文本消息
    massage_handle = MessageHandler(filters.TEXT & ~filters.COMMAND, choose_handler)

    # 构建 bot 请在TOKEN中替换为你自己的机器人秘钥
    TOKEN = 'YOUR TOKEN'
    application = ApplicationBuilder().token(TOKEN).build()
    # 注册 handler
    application.add_handler(start_handler)
    application.add_handler(help_handler)
    application.add_handler(ohayo_handler)
    application.add_handler(massage_handle)

    # run!
    application.run_polling()


if __name__ == '__main__':
    main()

使用的API

电影wangpanAPI

URL:https://www.hhlqilongzhu.cn/api/ziyuan_nanfeng.php

请求参数

接口名称

是否必填

接口类型

接口说明

keysearch

string

关键词

完整版本创建telegram bot_API_04

返回参数

参数名称

参数类型

参数说明

title

text

视频标题

data_url

text

视频资源链接

返回示例
{
    "data": [
        {
            "title": "[龙珠超][2015][全集][动画]",
            "data_url": "链接:xxxx"
        },
        {
            "title": "[龙珠超:超级英雄][2022][动画][日本]",
            "data_url": "链接:xxxx 提取码:xxxx"
        }
    ],
    "count": 2
}
电影URL解析API

URL:https://xiaoapi.cn/API/jx_txsp.php

请求参数

参数名称

参数类型

是否必填

备注内容

url

text

需要解析的播放链接

返回参数

参数名称

参数类型

参数说明

code

text

状态码

title

text

视频标题

url

text

视频资源链接

返回示例
{
    "code": 200,
    "title": "破·局",
    "url": "xxxxxxxx"
}