Skip to content

Commit

Permalink
init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
anhao committed Feb 7, 2021
0 parents commit 8cbc1bd
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
## TG Bot
TG 消息推送机器人
67 changes: 67 additions & 0 deletions api/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php
header('content-type: application/json');
$type = $_REQUEST['type'] ?? 'message';
$token = $_REQUEST['token'] ?? null;
$message = $_REQUEST['message'] ?? '';

$bot = new Bot();
// webhook
if ($type === 'webhook') {
// 获取/token 命令,获取聊天 id
$data = json_decode(file_get_contents("php://input"), true);
$message = $data['message']['text'];
if ($message === '/token') {
$chat_id = $data['message']['chat']['id'];
$bot->sendMessage(['text' => $bot->encryption($chat_id), 'chat_id' => $chat_id]);
}
return json_encode(['code' => 200, 'message' => 'success']);
} else {
if (is_null($token)) {
return json_encode(['code' => 422, 'message' => 'token 不能为空']);
} else {
// 发送消息
$chat_id = $bot->decryption($token);
$ret = $bot->sendMessage(['text' => $message, 'chat_id' => $chat_id]);
if ($ret['ok']) {
return json_encode(['code' => 200, 'message' => 'success']);
} else {
return json_encode(['code' => 422, 'message' => 'error']);
}
}
}

class Bot
{
public string $key = "abc";
public string $token = "1679016407:AAEHII057c26C5_vY8tSLbO8G6mnyXUOYbM";

public function sendMessage($data): array
{
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => sprintf('https://api.telegram.org/bot%s/sendMessage', $this->token),
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 encryption($chat_id): string
{
return base64_encode($this->key . $chat_id);
}

public function decryption($text): string
{
return substr(base64_decode($text), strlen($this->key));
}
}
7 changes: 7 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"functions": {
"api/*.php": {
"runtime": "[email protected]"
}
}
}

0 comments on commit 8cbc1bd

Please sign in to comment.