Repository: anhao/TgMessage
Branch: main
Commit: 8ce2fbac680b
Files: 16
Total size: 60.1 KB
Directory structure:
gitextract_com7y8vo/
├── .edgeone/
│ └── project.json
├── .gitignore
├── LICENSE
├── README.md
├── api/
│ ├── Bot.php
│ ├── index.php
│ ├── setWebHook.php
│ └── webhook.php
├── edge_deploy/
│ └── edge.html
├── edgeone.json
├── functions/
│ ├── bot.js
│ ├── sendMessage.js
│ ├── setWebhook.js
│ └── webhook.js
├── index.html
└── vercel.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .edgeone/project.json
================================================
{
"Name": "tg-message",
"ProjectId": "pages-ywhm4l7gjx2i"
}
================================================
FILE: .gitignore
================================================
.vercel
.idea
.idea/
# Tencent Cloud EdgeOne
.env
.edgeone/*
!.edgeone/project.json
.tef_dist/*
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
[](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fanhao%2FTGMessage)
[](https://dashboard.pandastack.io/deploy?repo=anhao/TgMessage&type=static&buildCmd=npm+run+build&outputDir=dist)
[](https://edgeone.ai/pages/new?repository-url=https%3A%2F%2Fgithub.com%2Fanhao%2FTGMessage&project-name=tg-message&build-command=&install-command=&output-directory=edge_deploy&root-directory=./&env=token,sign_key&env-description=)
## 技术赞助
本项目 CDN 加速及安全防护由 Tencent EdgeOne 赞助:EdgeOne 提供长期有效的免费套餐,包含不限量的流量和请求,覆盖中国大陆节点,且无任何超额收费,感兴趣的朋友可以点击下面的链接领取
[亚洲最佳CDN、边缘和安全解决方案 - Tencent EdgeOne](https://edgeone.ai/zh?from=github&utm_source=TgMessage)
## 第一步:创建 Telegram 机器人 (公共教程)
在部署之前,您首先需要一个 Telegram Bot。
1. **关注 BotFather**: 在 Telegram 中搜索并关注官方的 [BotFather](https://t.me/BotFather)。
2. **创建机器人**:
* 向 BotFather 发送 `/newbot` 命令。
* 根据提示,依次输入机器人的显示名称(例如 `我的消息助手`)和用户名(必须以 `bot` 结尾,例如 `my_message_assistant_bot`)。

3. **获取 Token**: 创建成功后,BotFather 会发送一条包含 **API Token** 的消息。请务必保存好这个 Token,它在后续部署中是必需的。

4. **设置命令**: 为了方便获取 `chat_id`,需要为机器人设置一个命令。
* 向 BotFather 发送 `/mybots`,然后选择你刚刚创建的机器人。
* 点击 `Edit Bot` -> `Edit Commands`。
* 输入 `token - 获取个人 Token` 并发送。

---
## 第二步:选择平台进行部署
您可以选择 Vercel 或 腾讯云 EdgeOne 进行部署,两者择一即可。
### 选项 A:通过 Vercel 部署
Vercel 提供免费、快速的 Serverless 函数托管服务。
1. **一键部署**: 点击项目顶部的 **Deploy with Vercel** 按钮。
2. **设置环境变量**: 在 Vercel 的项目创建页面,你需要配置以下环境变量:
* `token`: **【必填】** 填入上一步获取的机器人 API Token。
* `sign_key`: **【建议】** 用于加密 `chat_id` 的密钥,不设置默认为 `abc`。建议设置为一个复杂的随机字符串。
* `key`: **【建议】** 设置 Webhook 时的管理密钥,防止他人调用。请设置为一个复杂的随机字符串。
* `url`: **【可选】** 你的 Webhook 回调地址。如果不设置,后续需要手动指定。Webhook 最终地址为 `https://<你的Vercel域名>/api/webhook`。

3. **获取个人 Token**:
* 部署完成后,在浏览器中访问 `https://<你的Vercel域名>/api/setWebhook?key=<你设置的key>` 来设置回调。
* 然后与你的机器人对话,发送 `/token` 命令,机器人会返回一长串加密的个人 Token。
4. **发送消息**:
* 现在你可以通过请求 `https://<你的Vercel域名>/api/index?token=<你的个人Token>&message=你好` 来给自己发送消息。
### 选项 B:通过 EdgeOne Page Functions 部署
EdgeOne 是腾讯云推出的边缘一体化安全与加速平台,其 Page Functions 功能同样可以托管本项目。

1. **一键部署 (推荐)**:
* 点击项目顶部的 **使用 EdgeOne Pages 部署** 按钮。
* 授权后,在项目创建页面,EdgeOne 会自动为你填充大部分配置。
* 在 **环境变量** 部分,填入 `token` 和 `sign_key`。
* **重要**: 部署启动后,请立即进入项目 "设置" -> "环境变量" 页面,**手动添加**第三个环境变量 `key`。
* **环境变量说明**:
* `token`: **【必填】** 你的 Telegram Bot Token。
* `sign_key`: **【必填】** 加密 `chat_id` 用的密钥。
* `key`: **【必填】** 设置 Webhook 用的管理密钥。
2. **手动部署**:
* Fork 本项目到你的 GitHub 账户。
* 在 EdgeOne 控制台新建 Pages 项目,关联你 Fork 的仓库。
* **输出目录** 填写 `edge_deploy`。
* 手动添加上述三个环境变量。
3. **获取个人 Token**:
* 部署成功后,在浏览器中访问 `https://<你的Pages域名>/setWebhook?key=<你设置的key>` 设置回调。
* 与你的机器人对话,发送 `/token` 命令,获取个人 Token。
4. **发送消息**:
* 通过访问 `https://<你的Pages域名>/sendMessage?token=<你的个人Token>&message=你好` 发送消息。
* API 详情可参考 `edge_deploy/edge.html`。
## Vercel 版本
TG 消息推送机器人,基于 vercel 函数 和 Edgeone 边缘函数 搭建的TG消息推送机器人,无需服务器。
## 搭建教程
### Deploy to Vercel
[](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fanhao%2FTgMessage&env=token,sign_key,key&project-name=tg-message&repo-name=tg-message&demo-title=TG%20Message&demo-url=https%3A%2F%2Ftg-message.vercel.app%2F)
[](https://dashboard.pandastack.io/deploy?repo=anhao/TgMessage&type=static&buildCmd=npm+run+build&outputDir=dist)
### 建立 TG 机器人
1.首先关注 [BotFather](https://t.me/BotFather)
2. 创建机器人,关注 BotFather 之后,发送 `/newboot` 开始创建 Bot 第一次输入机器人名称,第二次输入机器人 `username` 需要以 `bot` 结尾

**3.获取机器人 token**
创建成功之后会发送一条消息给你,里面就包含了 `token`

**设置机器人 Command**
设置获取 token 命令 首先给 BotFather 发送 `/mybots`,然后点击你刚才创建的机器人,再点击 `Edit Bot`, 继续点击 `Edit Commands`。 然后输入
```
token - 获取token
```
这样就设置好了一个 `commands`




## 部署到 Vercel
点击首页的 Deploy 跳到 vercel

输入项目名,然后确认

确认之后会直接部署到 vercel
### 设置环境变量
vercel 部署好了之后,然后设置环境变量
在控制台点击你创建好的项目,然后点击设置,添加环境变量

```
需要设置4个环境变量,1个是必填的
token: bot 机器人的token
sign_key: 加密 chat_id 需要用到,不设置默认为 abc
url: webhook 回调地址, 不设置的话请求 setWebhook 时需要手动加参数, webhook url 地址为:https://你的域名/webhook
key: 设置 webhook 的请求参数
```

上面的环境变量设置好了之后,可能不会立马生效,你可以重新构建一下函数

### 设置回调
设置 webhook ,可以直接通过浏览器请求来设置
webhook地址为:`https://你的域名/webhook`
浏览器窗口打开:`https://你的域名/setwebhook?key=环境变量设置的KEY&url=你的webhook地址`
`code` 返回 200 就是设置成功了~
================================================
FILE: api/Bot.php
================================================
token = $_ENV['token'];
$this->key = $_ENV['sign_key'] ?? 'abc';
}
public function request($method, $data)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => sprintf('https://api.telegram.org/bot%s/%s', $this->token, $method),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $data,
));
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
public function sendMessage($data): array
{
return $this->request('sendMessage', $data);
}
public function setWebHook($data)
{
return $this->request('setWebhook', $data);
}
public function encryption($chat_id): string
{
return base64_encode($this->key . $chat_id);
}
public function decryption($text): string
{
return substr(base64_decode($text), strlen($this->key));
}
/**
* @param string $key
* @return Bot
*/
public function setKey(string $key): Bot
{
$this->key = $key;
return $this;
}
/**
* @param string $token
* @return Bot
*/
public function setToken(string $token): Bot
{
$this->token = $token;
return $this;
}
}
================================================
FILE: api/index.php
================================================
422, 'message' => 'token 不能为空']);
} else {
// 发送消息
$chat_id = $bot->decryption($token);
$ret = $bot->sendMessage(['text' => $message, 'chat_id' => $chat_id]);
if ($ret['ok']) {
echo json_encode(['code' => 200, 'message' => 'success']);
} else {
echo json_encode(['code' => 422, 'message' => $ret['description']]);
}
}
================================================
FILE: api/setWebHook.php
================================================
422, 'message' => '设置秘钥错误']);
} else {
//开始设置回调url
$url = $_REQUEST['url'] ?? $_ENV['url'];
require_once 'Bot.php';
$data = ['url' => $url];
$bot = new Bot();
$ret = $bot->setWebHook($data);
if ($ret['ok']) {
echo json_encode(['code' => 200, 'message' => '设置成功']);
} else {
echo json_encode(['code' => 422, 'message' => $ret['description']]);
}
}
================================================
FILE: api/webhook.php
================================================
sendMessage(['text' => $bot->encryption($chat_id), 'chat_id' => $chat_id]);
}
echo json_encode(['code' => 200, 'message' => 'success']);
================================================
FILE: edge_deploy/edge.html
================================================
你的边缘函数触发地址, 例如:
https://your-domain.com/
/token 获取你的专属 Token.token, sign_key, key.| 字段名称 | 类型 | 必填 | 备注 |
|---|---|---|---|
| token | string | Y | 从机器人获取的 Token |
| message | string | Y | 要发送的消息内容 |
请求示例:
GET /sendMessage?token=YOUR_TOKEN&message=Hello+World
| 字段名称 | 类型 | 必填 | 备注 |
|---|---|---|---|
| key | string | Y | 你在环境变量中设置的 key |
| url | string | N | 可选, 自定义 webhook 地址, 默认为当前函数地址 + /webhook |
请求示例:
GET /setWebhook?key=YOUR_ADMIN_KEY
此接口用于接收来自 Telegram 的 POST 请求,通常无需手动调用。
{"code":200,"message":"success"}
/token 获取 token | 字段名称 | 字段说明 | 类型 | 必填 | 备注 |
|---|---|---|---|---|
| token | string | Y | token | |
| message | string | Y | 要发送的消息内容 |
{"code":200,"message":"success"}