- php server send telegram message by bot
* 봇 생성
검색에서 @botfather 검색
botFather 선택하고 /newbot 메시지 전송
봇이름 , 봇의 사용자 이름 입력
생성된 토큰 기억
* 봇 설정(옵션)
초기 설정은 /로 시작하는 메시지만 받을수 있다. 모든 일반 메시지도 받을 경우
@BotFather 에게 /setprivacy 메시지 전송
Disable 전송
* 봇의 메시지 수신 설정 (옵션)
Webhook(웹훅)
webhook 등록
https://api.telegram.org/bot토큰/setwebhook?url=https://받을경로
webhook 등록 삭제
https://api.telegram.org/bot토큰/setwebhook
//-----------------
* 메시지 보내기
<?php
$token = "토큰";
$path = "https://api.telegram.org/bot".$token;
$msg = $_REQUEST['msg']??'';
$id = $_REQUEST['id']??'';
file_get_contents($path."/sendmessage?chat_id=".$id."&text=".$msg);
?>
//----------------
* 메시지 수신 응답(웹훅)
<?php
$token = "토큰";
$path = "https://api.telegram.org/bot".$token;
$update = json_decode(file_get_contents("php://input"), TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
if (strpos($message, "/hello") == 0) {
$reply = "hi i'm bot";
file_get_contents($path."/sendmessage?chat_id=".$chatId."&text=".$reply);
}
?>
//----------------------
* 사용자의 chat_id 알아내기
그룹에 @RawDataBot 을 초대하면 알아낼수있다.
//---------------
* 에러
- 에러 메시지
Forbidden: bot can't initiate conversation with a user
- 해결방법
- 처음 한번은 실제 사용자가 봇에게 메시지를 보내야 한다.
- 봇과의 대화창을 유지해야 봇의 메시지를 받을수 있다.
//-----------
// 참고
https://github.com/php-telegram-bot/core
https://nordicapis.com/how-to-build-your-first-telegram-bot-using-php-in-under-30-minutes/
https://core.telegram.org/bots/api
https://core.telegram.org/bots/api#sendmessage
https://stackoverflow.com/questions/32423837/telegram-bot-how-to-get-a-group-chat-id
'Code > PHP' 카테고리의 다른 글
[라라벨] 큐 사용법(Queue, Job, Horizon) (0) | 2020.03.24 |
---|---|
php 7.3 PCNTL 확장 기능 활성화 방법 (0) | 2020.03.24 |
[php] 서버에서 텔레그램 메시지 전송 (0) | 2020.03.19 |
[php] PHP 7.4의 새로운 기능 (0) | 2020.03.12 |
[php] PHP 7.4에서 삭제예정으로 정해진 기능(Deprecated) (0) | 2020.03.12 |
[php] OpCache 설정 (0) | 2020.03.11 |
댓글을 달아 주세요