最初のテレグラムボットの構築:ステップバイステップガイド

公開: 2022-03-11

チャットボットは、ユーザーがテクノロジーやビジネスとやり取りする方法の革命として宣伝されることがよくあります。 従来のアプリと比較して、ユーザーがチャットするだけでよいため、インターフェースはかなりシンプルです。チャットボットは、少なくとも理論上は、ユーザーが要求することをすべて理解して実行することになっています。

多くの業界は、顧客サービスをチャットボットシステムにシフトしています。 これは、実際の人間と比較してコストが大幅に低下していることと、堅牢性と継続的な可用性のためです。 チャットボットは、実質的な追加コストなしである程度のユーザーサポートを提供します。

今日、チャットボットは、時間や天気のデータの表示などの単純なタスクから、基本的な医療診断や顧客とのコミュニケーション/サポートなどのより複雑な操作に至るまで、多くのシナリオで使用されています。 顧客が製品について特定の質問をするときに役立つチャットボットを考案することも、基本的なタスクを処理して会議やジムに行くときに思い出させることができるパーソナルアシスタントチャットボットを作成することもできます。

チャットボットを展開できる場所に関しては多くのオプションがあり、ほとんどの人が定期的に使用するため、最も一般的な用途の1つはソーシャルメディアプラットフォームです。 インスタントメッセージングアプリについても同じことが言えますが、いくつかの注意点があります。

Telegramは、デバイスだけでなくクラウドにメッセージを保存できるため、今日最も人気のあるIMプラットフォームの1つであり、Android、iOS、WindowsなどでTelegramを使用できるため、優れたマルチプラットフォームサポートを誇っています。 Webバージョンをサポートできるその他のプラットフォーム。 Telegramでチャットボットを構築するのは非常に簡単で、完了までにほとんど時間がかからないいくつかの手順が必要です。 チャットボットはTelegramグループおよびチャネルに統合でき、それ自体でも機能します。

このチュートリアルでは、愛らしいアバターからアバター画像を提供するテレグラムボットを作成します。 この例では、Flaskを使用してボットを構築し、それを無料のHerokuサーバーにデプロイします。

このチュートリアルを完了するには、Python3がシステムにインストールされていることとPythonコーディングスキルが必要です。 また、アプリがどのように機能するかをよく理解することは良い追加ですが、私たちが提示するほとんどのことを詳細に説明するので、必須ではありません。 また、システムにGitをインストールする必要があります。

もちろん、チュートリアルには無料のTelegramアカウントも必要です。 こちらからサインアップできます。 Herokuアカウントも必要であり、ここから無料で入手できます。

テレグラムボットに命を吹き込む

Telegramでチャットボットを作成するには、基本的に他のボットを作成するために使用されるボットであるBotFatherに連絡する必要があります。

必要なコマンドは/newbotで、ボットを作成するための次の手順につながります。

テレグラムボットチュートリアル-スクリーンショットの例

ボットには、名前とユーザー名の2つの属性が必要です。 ボットの名前が表示され、ユーザー名はメンションと共有に使用されます。

ボット名とユーザー名(「bot」で終わる必要があります)を選択すると、アクセストークンを含むメッセージが表示されます。アクセストークンとユーザー名は、必要になるため、後で使用できるように保存する必要があります。

チャットボットロジックをコーディングする

このチュートリアルではUbuntuを使用します。 Windowsユーザーの場合、ここにあるほとんどのコマンドは問題なく機能しますが、仮想環境のセットアップで問題が発生した場合は、このリンクを参照してください。 Macユーザーの場合、このチュートリアルは問題なく機能するはずです。

まず、仮想環境を作成しましょう。 プロジェクトの要件をグローバルなPython環境から分離するのに役立ちます。

 $ python -m venv botenv/

これで、使用するすべてのPythonライブラリを含むbotenv/ディレクトリが作成されます。 次のコマンドを使用して、 virtualenvをアクティブにします。

 $ source botenv/bin/activate

ボットに必要なライブラリは次のとおりです。

  • Flask:Pythonで構築されたマイクロWebフレームワーク。
  • Python-telegram-bot:Pythonのテレグラムラッパー。
  • リクエスト:人気のあるPythonhttpライブラリ。

次のようにpipコマンドを使用して仮想環境にインストールできます。

 (telebot) $ pip install flask (telebot) $ pip install python-telegram-bot (telebot) $ pip install requests

それでは、プロジェクトディレクトリを参照してみましょう。

 . ├── app.py ├── telebot │ ├── credentials.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv

credentials.pyファイルには、次の3つの変数が必要です。

 bot_token = "here goes your access token from BotFather" bot_user_name = "the username you entered" URL = "the heroku app link that we will create later"

それでは、app.pyに戻って、コードを段階的に見ていきましょう。

 # import everything from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL
 global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN)

これで、ボットに実行する必要のあるアクションに使用されるボットオブジェクトができました。

 # start the flask app app = Flask(__name__)

また、関数を特定のルートにバインドする必要があります。 つまり、特定のアドレスが呼び出されたときに何をするかをFlaskに指示する必要があります。 フラスコとルートの詳細については、こちらをご覧ください。

この例では、route関数は基本的に/{token}であるURLに応答します。これは、ボットに送信されたメッセージの応答を取得するためにTelegramが呼び出すURLです。

 @app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok'

この関数を機能させる直感的な方法は、毎秒呼び出すことで、新しいメッセージが到着したかどうかをチェックしますが、それは行いません。 代わりに、メッセージが呼び出されるたびにボットにサーバーを呼び出させる方法を提供するWebhookを使用します。これにより、メッセージが来るのを待つwhileループでサーバーを苦しめる必要がなくなります。

そこで、TelegramのWebhookをアクティブにするために自分で呼び出す必要のある関数を作成します。基本的には、新しいメッセージが到着したときに特定のリンクを呼び出すようにTelegramに指示します。 この関数は、最初にボットを作成するときに1回だけ呼び出します。 アプリのリンクを変更した場合は、新しいリンクを使用してこの関数を再度実行する必要があります。

ここでのルートは何でもかまいません。 あなたはそれを呼ぶ人です:

 @app.route('/setwebhook', methods=['GET', 'POST']) def set_webhook(): # we use the bot object to link the bot to our app which live # in the link provided by URL s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) # something to let us know things work if s: return "webhook setup ok" else: return "webhook setup failed"

すべてが設定されたので、エンジンが稼働していることを確認できるように、見栄えのするホームページを作成しましょう。

 @app.route('/') def index(): return '.' if __name__ == '__main__': # note the threaded arg which allow # your app to have more than one thread app.run(threaded=True)

app.pyのフルバージョンを見てみましょう。

 import re from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN) app = Flask(__name__) @app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok' @app.route('/set_webhook', methods=['GET', 'POST']) def set_webhook(): s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) if s: return "webhook setup ok" else: return "webhook setup failed" @app.route('/') def index(): return '.' if __name__ == '__main__': app.run(threaded=True)

これが、チュートリアルで作成するコードの最後のビットです。 これで、Herokuでアプリを起動して、最後のステップに進むことができます。

Herokuでアプリを起動する

アプリを作成する前に、いくつか必要なことがあります。

Herokuはプロジェクトで使用されているライブラリを認識できないため、 requirements.txtファイルを使用して通知する必要があります。一般的な問題は要件のスペルを間違えることです。注意してください。pipを使用して要件ファイルを生成します。

 pip freeze > requirements.txt

これで、要件ファイルの準備が整いました。

ここで、Herokuにアプリの起動場所を通知するProcfileが必要なので、 Procfileファイルを作成し、以下を追加します。

 web: gunicorn app:app

バウンス手順:プロジェクトに.gitignoreファイルを追加して、使用しないファイルがリポジトリにアップロードされないようにすることができます。

Herokuダッシュボードから、新しいアプリを作成します。 実行すると、[デプロイ]ページに移動します。 次に、新しいウィンドウで[設定]タブを開き、 https://appname.herokuapp.com/のようなアプリのドメインをコピーして、 credentials.py内のURL変数に貼り付けます。

Herokuダッシュボードのスクリーンショット

次に、[デプロイ]タブに戻り、次の手順に進みます。

注: WindowsおよびmacOSユーザーは、ここで説明する手順に従うことができます。

Herokuにログインします。

 $ heroku login

このメソッドwaiting for loginスタックすることがあることに注意してください。これが発生した場合は、次を使用してログインしてみてください。

 $ heroku login -i

ディレクトリでGitリポジトリを初期化します。

 $ git init $ heroku git:remote -a {heroku-project-name}

アプリをデプロイします。

 $ git add . $ git commit -m "first commit" $ git push heroku master

この時点で、ターミナルで建物の進行状況が表示されます。 すべてがうまくいけば、次のようなものが表示されます。

 remote: -----> Launching... remote: Released v6 remote: https://project-name.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done.

次に、アプリページ(前にコピーしたドメインのリンク)に移動し、リンクの最後に/setwebhookを追加して、アドレスがhttps://appname.herokuapp.com/setwebhookのようになるようにします。 webhook setup okに問題がない場合は、準備ができていることを意味します。

今すぐあなたのボットと話してください

Telegramチャットボットのライブバージョン
ボットのライブバージョン

最後の仕上げ、ヒント、およびコツ

これで、Telegramボットが24時間年中無休で稼働し、介入する必要がなくなりました。 ボットには任意のロジックを追加できます。たとえば、次のように「入力中」ステータスを追加して写真ステータスを送信することで、ボットをより現実的にすることができます。

response respond()関数からの次のコードスニペット:

 if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendChatAction(chat_id=chat_id, action="typing") sleep(1.5) bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendChatAction(chat_id=chat_id, action="upload_photo") sleep(2) bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

スニペットでわかるように、テキスト形式のボットに関する情報を送信しようとしているときに入力アクションを追加し、ボットをより現実的にするために写真を送信しようとしているときに写真のアップロードアクションを追加しました。 その他のアクションはここにあります。

BotFatherチャネルからボットの画像と説明を変更して、より親しみやすくすることもできます。

テレグラムボットのさらに多くの簡単な例は、GitHubのpython-telegram-botページにあります。

ボットを基にして、次のスーパーAIボットにすることができます。必要なのは、ロジックをrespond()関数に統合することだけです。 たとえば、ロジックを別のモジュールに配置して、次のようにrespond()関数内で呼び出すことができます。

 . ├── app.py ├── telebot │ ├── credentials.py │ ├──ai.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv

そしてai.pyの内部:

 def generate_smart_reply(text): # here we can do all our work return "this is a smart reply from the ai!"

今すぐapp.pyにインポートしてください:

 import re from time import sleep from flask import Flask, request import telegram From telebot.ai import generate_smart_reply from telebot.credentials import bot_token, bot_user_name,URL

次に、 respond()コード内で呼び出します。

 def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # here call your smart reply message reply = generate_smart_reply(text) bot.sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)

これで、ボットを思いどおりに動作させることができます。先に進んで、次の大きなものを作成してください。

最初のTelegramボットの作成を楽しんでいただけたでしょうか。

追加リソース

  • TelegramとPythonを使用したチャットボットの構築
  • TelegramBotWebHookを簡単に設定する
  • Python-telegram-botリポジトリ
  • HerokuにGitを使用してデプロイする
  • PythonTelegramBotのドキュメント
関連:アプリではなく、WhatsAppチャットボットを作成する