简单快速部署一个tg ai bot

应该算是0成本吧。

准备

必需的

  • Hugging Face账号。
  • Telegram账号。
  • Serv00账号。(不需要占用系统资源。但是也许不是必需的,看后面吧。)

可选的

  • api
  • webdav

开始

1. 创建一个tg bot

Telegram: Contact @botfather,根据他的提示创建bot,创建成功后会给你一个类似xxx:xxx的token。保存好,这是TELEGRAM_BOT_TOKEN。

2. 搞一个tg代理

因为hf好像禁了tg(好像是?小白也不知道呀),所以要搞一个代理,我使用的是serv00。复制这个到index.php。

<?php
$allowed_hosts = array("api.telegram.org", "telegram.org");

$url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parsed_url = parse_url($url);
$host = $parsed_url['host'];

if (isset($parsed_url['path']) && strpos($parsed_url['path'], '/health') !== false && $_SERVER['REQUEST_METHOD'] == 'GET') {
    echo 'OK';
    exit;
}

$telegram_api_url = "https://api.telegram.org";

$request_url = str_replace($parsed_url['scheme'] . "://" . $parsed_url['host'], $telegram_api_url, $url);

$headers = getallheaders();
$new_headers = array();
foreach ($headers as $key => $value) {
    if ($key != 'Host') {
        $new_headers[] = "$key: $value";
    }
}

$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $new_headers);
curl_setopt($ch, CURLOPT_HEADER, true);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
}

$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);

$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$headers_array = explode("\r\n", $headers);
foreach ($headers_array as $header) {
    if (!empty($header)) {
        header($header);
    }
}

http_response_code($http_code);
echo $body;
?>

如果你有别的也行。

3. 部署hf空间

Chat – a Hugging Face Space by yangtb24,点击这个链接进去,填写相关信息。必填的TELEGRAM_BOT_TOKEN(刚才创建的)和PHP_PROXY_URL(serv00创建的那个)。ai可以不填,如果你有也可以填,自带硅基key。如果你有备份需求,可以填写webdav(hf重启空间丢数据)。

4. 设置bot webhook

访问https://api.telegram.org/bot你的token/setWebhook?url=https://你的hf空间.hf.space/。再去tg看你的bot就可以聊天了(也可以拉进群组),如果不行的话重启一下空间(有时候就是不行,我也不知道为什么)。

最后

这个bot可能功能比较少,可能也有小问题。大佬们可以自己根据需求改改。

在代码里面有个PROMPT_TEMPLATES,可以自己加要的提示词。

如果你想试用,可以找Telegram: Contact @zfs732_bot试一试。

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注