Closed5

Telethon Bot APIを使ってみる

Shige OsadaShige Osada

とりあえず環境を最新化

% brew update
% brew upgrade

チュートリアルに従いながら挑戦

https://core.telegram.org/bots/tutorial

BOTアカウントの作成

Obtaining a token is as simple as contacting @BotFather, issuing the /newbot command

BOTの名前を入れると、対応するトークンが出力される。

チュートリアルコード

Javaが標準で書かれているが、Pythonのコードもある。
https://gitlab.com/Athamaxy/telegram-bot-tutorial/-/blob/main/TutorialBot.py

Pythonの環境

pip + virtualenv (venv)を併せ持つpipenvを使う。
pipenvは、Pipfileで環境を定義できる。
詳しくは以下
https://qiita.com/y-tsutsu/items/54c10e0b2c6b565c887a

% cd ~/bot
% pip install pipenv
% pipenv --python 3.9
% pipenv install python-telegram-bot==13.12
% pipenv run python3 bot.py

bot.pyはチュートリアルから持ってくる

Shige OsadaShige Osada

Telegram bot

https://pypi.org/project/python-telegram-bot/

Troubleshoot

TypeError: __init__() missing 1 required positional argument: 'update_queue'

わからない。

import系エラーは以下のように修正。
ParseModeはtelegram.costantsに、Filtersは小文字のfiltersに修正。

from telegram import Update, ForceReply, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Updater, CommandHandler, MessageHandler, filters, CallbackContext, CallbackQueryHandler
from telegram.constants import ParseMode
Shige OsadaShige Osada

Telegram Client APIのバージョン

v13系とv20系は互換性が低いとのことなので、bot操作機能の実績が豊富なv13を選択する。
Telegram Server API(公式では単にTelegram APIと表記)のバージョンは、どちらもv6.6。

v13.15が最新か。

IntelliJの設定

今回使用したいtelegram.extは、python-telegram-botというパッケージ名になっている。
類似パッケージが多いので注意すること。
python-telegram-bot-rawではない。

Shige OsadaShige Osada

#改めて、python-telegram-botをインストールする

[ 23-04-12 8:37 ] ~/study/CCRPJ/sns-phish-mon/bot
osada@mbp20i% pipenv install python-telegram-bot==13.15   
Installing python-telegram-bot==13.15...
Adding python-telegram-bot to Pipfile's [packages]...
✔ Installation Succeeded 
Pipfile.lock (02982f) out of date, updating to (0ebff5)...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success! 
Updated Pipfile.lock (0ebff5)!
Installing dependencies from Pipfile.lock (0ebff5)...
  🐍   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/0 — 00:00:00
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

動いた!

def chat_info(update, bot):
    chat_id = update.message.chat_id
    date = update.message.date
    update.message.reply_text("chat id = " + str(chat_id)
                              + "\ndate = " + str(date) + "\n"
                              + update.message.text)

対象のbotにチャットすると、チャットIDが返される。

このスクラップは2023/06/15にクローズされました