ボットの登録が済み、APIトークンの発行ができたら次はプログラムを用意します。
ゼロからコードを書いてもいいのですが、まずは早くボットが動くところを見たいと思いますので、ここではサンプルコードを使わせてもらいましょう。
なお、ここではPHPで作成していきます。
HolloBotのコードをコピーして保存する
公式のBots FAQより
I’m a developer. Where can I find some examples?
Here are two sample bots, both written in PHP:・Hello Bot demonstrates the basics of the Telegram bot API.
・Simple Poll bot is a more complete example, it supports both long-polling and Webhooks for updates.
サンプルボットはいくつか有りますが、最初は一番シンプルなHelloBotを使います。
Simple Poll botもありますが、少し複雑なプログラムになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
<?php /* 2017/06/08 時点のコード https://core.telegram.org/bots/samples/hellobot テレグラム公式サイトから使わせていただいています */ define('BOT_TOKEN', '12345678:replace-me-with-real-token'); define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/'); function apiRequestWebhook($method, $parameters) { if (!is_string($method)) { error_log("Method name must be a string\n"); return false; } if (!$parameters) { $parameters = array(); } else if (!is_array($parameters)) { error_log("Parameters must be an array\n"); return false; } $parameters["method"] = $method; header("Content-Type: application/json"); echo json_encode($parameters); return true; } function exec_curl_request($handle) { $response = curl_exec($handle); if ($response === false) { $errno = curl_errno($handle); $error = curl_error($handle); error_log("Curl returned error $errno: $error\n"); curl_close($handle); return false; } $http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE)); curl_close($handle); if ($http_code >= 500) { // do not wat to DDOS server if something goes wrong sleep(10); return false; } else if ($http_code != 200) { $response = json_decode($response, true); error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n"); if ($http_code == 401) { throw new Exception('Invalid access token provided'); } return false; } else { $response = json_decode($response, true); if (isset($response['description'])) { error_log("Request was successfull: {$response['description']}\n"); } $response = $response['result']; } return $response; } function apiRequest($method, $parameters) { if (!is_string($method)) { error_log("Method name must be a string\n"); return false; } if (!$parameters) { $parameters = array(); } else if (!is_array($parameters)) { error_log("Parameters must be an array\n"); return false; } foreach ($parameters as $key => &$val) { // encoding to JSON array parameters, for example reply_markup if (!is_numeric($val) && !is_string($val)) { $val = json_encode($val); } } $url = API_URL.$method.'?'.http_build_query($parameters); $handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($handle, CURLOPT_TIMEOUT, 60); return exec_curl_request($handle); } function apiRequestJson($method, $parameters) { if (!is_string($method)) { error_log("Method name must be a string\n"); return false; } if (!$parameters) { $parameters = array(); } else if (!is_array($parameters)) { error_log("Parameters must be an array\n"); return false; } $parameters["method"] = $method; $handle = curl_init(API_URL); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($handle, CURLOPT_TIMEOUT, 60); curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters)); curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); return exec_curl_request($handle); } function processMessage($message) { // process incoming message $message_id = $message['message_id']; $chat_id = $message['chat']['id']; if (isset($message['text'])) { // incoming text message $text = $message['text']; if (strpos($text, "/start") === 0) { apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array( 'keyboard' => array(array('Hello', 'Hi')), 'one_time_keyboard' => true, 'resize_keyboard' => true))); } else if ($text === "Hello" || $text === "Hi") { apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you')); } else if (strpos($text, "/stop") === 0) { // stop now } else { apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool')); } } else { apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages')); } } define('WEBHOOK_URL', 'https://my-site.example.com/secret-path-for-webhooks/'); if (php_sapi_name() == 'cli') { // if run from console, set or delete webhook apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL)); exit; } $content = file_get_contents("php://input"); $update = json_decode($content, true); if (!$update) { // receive wrong update, must not happen exit; } if (isset($update["message"])) { processMessage($update["message"]); } |
一番シンプルと言ったのに、結構長いですね。
最初のうちは何をしているかわからないかもしれませんが、とりあえず7行目と146行目(ハイライトしてあるところ)だけ書き換えて、phpファイルとして保存しましょう。
書き換え方は、前のページで発行したアクセストークン(7行目)と、公開するファイルのパス(146行目)を書き換える形になります。
公開するパスがまだわからない場合はあとで直せばいいので、とりあえずトークンだけ書き換えて、ファイルを「hellobot.php」と名前をつけて保存し次に進みましょう。
「ボット用プログラムの用意」に関するコメント
質問したいことがありますので、質問させて頂きます。
telegramで、相手が自分に対してEmailを送信したら、自動的に
telegramに転送させるプログラムを書きたいのです。
何卒よろしくお願いします。
どの辺りがわからないのでしょう。
メールをトリガーにプログラムを起動する(メールの文章をプログラムに渡す)
プログラムからtelegramにsendMessageかなにかで文章をポストする
くらいの手順でできそうな気がしますが、どちらも全く見当がつかない状態だとちょっと難しいかもしれません。
あまり詳しくないですが、1.はメールを受信するサーバー側の機能が必要になるはず。