pytelegrambotapi
Telegram Bot APIのシンプルだが拡張可能なPython実装。
同期と非同期の両方。
サポートされているボットAPIバージョン:7.1!
このAPIは、Python 3.8-3.12とPypy 3でテストされています。ライブラリをインストールするには2つの方法があります。
$ pip install pyTelegramBotAPI
$ pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git
通常、最初のオプションを使用することをお勧めします。
APIは生産対応ですが、まだ開発中であり、定期的な更新があります。電話をかけて定期的に更新することを忘れないでください
pip install pytelegrambotapi --upgrade
@botfatherとのAPIトークンを取得したと推定されます。このトークンTOKENと呼びます。さらに、Pythonプログラミング言語、さらに重要なことにTelegram Bot APIの基本的な知識があります。
テレボットクラス(__init__.pyで定義)は、単一のクラスのすべてのAPI呼び出しをカプセル化します。 send_xyz ( send_message 、 send_documentなど)などの関数と、着信メッセージを聞くためのいくつかの方法を提供します。
echo_bot.pyというファイルを作成します。次に、ファイルを開き、テレボットクラスのインスタンスを作成します。
import telebot
bot = telebot . TeleBot ( "TOKEN" , parse_mode = None ) # You can set parse_mode by default. HTML or MARKDOWN注:実際にトークンを独自のAPIトークンに置き換えてください。
その宣言の後、いわゆるメッセージハンドラーを登録する必要があります。メッセージハンドラーは、メッセージが渡す必要があるフィルターを定義します。メッセージがフィルターに合格すると、装飾された関数が呼び出され、着信メッセージは引数として渡されます。
着信/startおよび/helpコマンドを処理するメッセージハンドラーを定義しましょう。
@ bot . message_handler ( commands = [ 'start' , 'help' ])
def send_welcome ( message ):
bot . reply_to ( message , "Howdy, how are you doing?" )メッセージハンドラーによって装飾された関数は、任意の名前を持つことができますが、パラメーター(メッセージ)が1つだけ必要です。
別のハンドラーを追加しましょう:
@ bot . message_handler ( func = lambda m : True )
def echo_all ( message ):
bot . reply_to ( message , message . text )これは、すべての着信テキストメッセージを送信者にエコーします。 Lambda関数を使用してメッセージをテストします。 Lambdaがtrueを返す場合、メッセージは装飾された関数によって処理されます。すべてのメッセージをこの関数によって処理することを望んでいるため、単にtrueを返すだけです。
注:すべてのハンドラーは、宣言された順序でテストされます
これで、「/start」および「/help」コマンドに静的メッセージを返信し、送信されたメッセージの残りの部分を反映する基本的なボットがあります。ボットを起動するには、ソースファイルに次のことを追加します。
bot . infinity_polling ()さて、それだけです!私たちのソースファイルは今、次のようになります:
import telebot
bot = telebot . TeleBot ( "YOUR_BOT_TOKEN" )
@ bot . message_handler ( commands = [ 'start' , 'help' ])
def send_welcome ( message ):
bot . reply_to ( message , "Howdy, how are you doing?" )
@ bot . message_handler ( func = lambda message : True )
def echo_all ( message ):
bot . reply_to ( message , message . text )
bot . infinity_polling ()ボットを起動するには、端末を開き、 python echo_bot.pyを入力してボットを実行してください!コマンド( '/start'および '/help')と任意のテキストメッセージを送信してテストします。
すべてのタイプは、types.pyで定義されています。それらはすべて、Telegram APIのタイプの定義と完全に一致しています。ただし、 from_userに改名されたフィールドfromメッセージを除きます(Python予約トークンfrom )。したがって、 message_idなどの属性は、 message.message_idで直接アクセスできます。 message.chatは、 UserまたはGroupChatのインスタンスのいずれかにすることができることに注意してください(メッセージのユーザーとGroupChatを区別するにはどうすればよいですか?)。
メッセージオブジェクトには、メッセージのタイプを定義するcontent_type属性もあります。 content_typeは、 text 、 audio 、 document 、 animation 、 game 、 photo 、 sticker 、 video 、 video_note 、 voice 、 location 、 contact先、 venue 、 dice 、 new_chat_members 、 left_chat_member 、 new_chat_title 、 new_chat_photo 、 group_chat_created 、supergreated、delete_chat_chat_chat_title、new_chat_title、 delete_chat_photo 、new_chat_title、 supergroup_chat_created 、 channel_chat_created 、 migrate_to_chat_id 、 migrate_from_chat_id 、 pinned_message 、 invoice 、 successful_payment video_chat_participants_invited connected_website 、 poll 、 passport_data 、 proximity_alert_triggered 、 video_chat_scheduled 、 video_chat_ended 、 video_chat_started web_app_data 、 message_auto_delete_timer_changed 、 forum_topic_created 、 forum_topic_closed 、 forum_topic_reopened 、 forum_topic_edited 、 general_forum_topic_hidden 、 general_forum_topic_unhidden 、 write_access_allowed 、chat、chat、chat、chat、 story 、 user_shared 、 chat_shared 、
1つの関数でいくつかのタイプを使用できます。例:
content_types=["text", "sticker", "pinned_message", "photo", "audio"]
すべてのAPIメソッドは、テレボットクラスにあります。それらは、一般的なPythonの命名規則に従うように改名されます。たとえば、 getMe get_meに変更され、 sendMessageにsend_messageに変更されます。
以下に概説して、APIの一般的なユースケースがいくつかあります。
メッセージハンドラーは、テレボットインスタンスのmessage_handlerデコレーターで装飾された関数です。メッセージハンドラーは、1つまたは複数のフィルターで構成されています。メッセージハンドラーがそのメッセージを処理する資格を得るためには、各フィルターが特定のメッセージに対してTrueを返す必要があります。メッセージハンドラーは次の方法で宣言されます( botテレボットのインスタンスである場合):
@ bot . message_handler ( filters )
def function_name ( message ):
bot . reply_to ( message , "This is a message handler" ) function_nameは制限に拘束されません。任意の関数名はメッセージハンドラーで許可されています。関数は、せいぜい1つの引数を受け入れる必要があります。これは、関数が処理する必要があるメッセージになります。 filters 、キーワード引数のリストです。フィルターは、次の方法で宣言されます。 name=argument 。 1つのハンドラーには複数のフィルターがある場合があります。テレボットは次のフィルターをサポートしています。
| 名前 | 議論 | 状態 |
|---|---|---|
| content_types | 文字列のリスト(デフォルト['text'] ) | True message.content_typeが文字列のリストに含まれています。 |
| regexp | 文字列としての正規表現 | True re.search(regexp_arg) True and message.content_type == 'text'を返します(python正規式を参照) |
| コマンド | 文字列のリスト | True message.content_type == 'text'とmessage.textは、文字列のリストにあるコマンドから始まります。 |
| chat_types | チャットタイプのリスト | True IF message.chat.typeフィルターのType |
| func | 関数(ラムダまたは関数リファレンス) | True lambdaまたは関数リファレンスがTrueを返す場合 |
フィルターとメッセージハンドラーを使用する例は次のとおりです。
import telebot
bot = telebot . TeleBot ( "TOKEN" )
# Handles all text messages that contains the commands '/start' or '/help'.
@ bot . message_handler ( commands = [ 'start' , 'help' ])
def handle_start_help ( message ):
pass
# Handles all sent documents and audio files
@ bot . message_handler ( content_types = [ 'document' , 'audio' ])
def handle_docs_audio ( message ):
pass
# Handles all text messages that match the regular expression
@ bot . message_handler ( regexp = "SOME_REGEXP" )
def handle_message ( message ):
pass
# Handles all messages for which the lambda returns True
@ bot . message_handler ( func = lambda message : message . document . mime_type == 'text/plain' , content_types = [ 'document' ])
def handle_text_doc ( message ):
pass
# Which could also be defined as:
def test_message ( message ):
return message . document . mime_type == 'text/plain'
@ bot . message_handler ( func = test_message , content_types = [ 'document' ])
def handle_text_doc ( message ):
pass
# Handlers can be stacked to create a function which will be called if either message_handler is eligible
# This handler will be called if the message starts with '/hello' OR is some emoji
@ bot . message_handler ( commands = [ 'hello' ])
@ bot . message_handler ( func = lambda msg : msg . text . encode ( "utf-8" ) == SOME_FANCY_EMOJI )
def send_something ( message ):
pass重要:すべてのハンドラーは、宣言された順序でテストされます
編集されたメッセージ@bot.edited_message_handler(filters) # <- passes a Message type object to your function
ハンドルチャネル投稿メッセージ@bot.channel_post_handler(filters) # <- passes a Message type object to your function
ハンドル編集されたチャネル投稿メッセージ@bot.edited_channel_post_handler(filters) # <- passes a Message type object to your function
コールバッククエリを処理します
@ bot . callback_query_handler ( func = lambda call : True )
def test_callback ( call ): # <- passes a CallbackQuery type object to your function
logger . info ( call )配送Queries @bot.shipping_query_handler() # <- passes a ShippingQuery type object to your function
Pre Checkoupt queries @bot.pre_checkout_query_handler() # <- passes a PreCheckoutQuery type object to your function
ハンドルポーリングの更新@bot.poll_handler() # <- passes a Poll type object to your function
世論調査の回答@bot.poll_answer_handler() # <- passes a PollAnswer type object to your function
チャットでボットのメンバーステータスの更新を処理@bot.my_chat_member_handler() # <- passes a ChatMemberUpdated type object to your function
チャット@bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your functionに合格します。すべての更新タイプを許可する場合は、 bot.polling() / bot.infinity_polling()でallowed_updates util.update_typesに設定します。
ハンドルチャット参加要求を使用して: @bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function
インラインモードの詳細。
これで、inline_handlerを使用してテレボットでインラインクエリを取得できます。
@ bot . inline_handler ( lambda query : query . query == 'text' )
def query_text ( inline_query ):
# Query message is text chosen_inline_handlerを使用して、テレボットでchosen_inline_resultを取得します。 @botfatherの /setInlineFeedbackコマンドを追加してはいけません。
詳細:収集フィードバック
@ bot . chosen_inline_handler ( func = lambda chosen_inline_result : True )
def test_chosen ( chosen_inline_result ):
# Process all chosen_inline_result. @ bot . inline_handler ( lambda query : query . query == 'text' )
def query_text ( inline_query ):
try :
r = types . InlineQueryResultArticle ( '1' , 'Result' , types . InputTextMessageContent ( 'Result message.' ))
r2 = types . InlineQueryResultArticle ( '2' , 'Result2' , types . InputTextMessageContent ( 'Result message2.' ))
bot . answer_inline_query ( inline_query . id , [ r , r2 ])
except Exception as e :
print ( e )ミドルウェアハンドラーは、テレグラムを通過するときにリクエストまたはボットコンテキストを変更できる関数です。ミドルウェアは、他のハンドラーが実行される前に処理されるロジック接続のチェーンとして想像できます。ミドルウェア処理はデフォルトで無効になり、 apihelper.ENABLE_MIDDLEWARE = Trueを設定して有効にします。
apihelper . ENABLE_MIDDLEWARE = True
@ bot . middleware_handler ( update_types = [ 'message' ])
def modify_message ( bot_instance , message ):
# modifying the message before it reaches any other handler
message . another_text = message . text + ':changed'
@ bot . message_handler ( commands = [ 'start' ])
def start ( message ):
# the message is already modified when it reaches message handler
assert message . another_text == message . text + ':changed'例/ミドルウェアディレクトリには、ミドルウェアハンドラーを使用して他の例があります。
クラスベースのミドルウェアがあります。基本的なクラスベースのミドルウェアは次のようになります:
class Middleware ( BaseMiddleware ):
def __init__ ( self ):
self . update_types = [ 'message' ]
def pre_process ( self , message , data ):
data [ 'foo' ] = 'Hello' # just for example
# we edited the data. now, this data is passed to handler.
# return SkipHandler() -> this will skip handler
# return CancelUpdate() -> this will cancel update
def post_process ( self , message , data , exception = None ):
print ( data [ 'foo' ])
if exception : # check for exception
print ( exception )クラスベースのミドルウェアには、投稿と事前プロセスの2つの機能が必要です。したがって、ご覧のとおり、クラスベースのMiddleWaresは、ハンドラーの実行の前後に機能します。詳細については、例をご覧ください
また、組み込みのカスタムフィルターを使用できます。または、独自のフィルターを作成できます。
また、カスタムフィルターの例にも、例があります。このリンクを確認してください。テキストによるフィルタリングの例でフィルタリングのソースコードの例を確認できます。ビルトインフィルターを追加する場合は、custom_filters.pyファイルに追加できます。これがフィルタークラスの作成例です。
class IsAdmin ( telebot . custom_filters . SimpleCustomFilter ):
# Class will check whether the user is admin or creator in group or not
key = 'is_chat_admin'
@ staticmethod
def check ( message : telebot . types . Message ):
return bot . get_chat_member ( message . chat . id , message . from_user . id ). status in [ 'administrator' , 'creator' ]
# To register filter, you need to use method add_custom_filter.
bot . add_custom_filter ( IsAdmin ())
# Now, you can use it in handler.
@ bot . message_handler ( is_chat_admin = True )
def admin_of_group ( message ):
bot . send_message ( message . chat . id , 'You are admin of this group!' ) import telebot
TOKEN = '<token_string>'
tb = telebot . TeleBot ( TOKEN ) #create a new Telegram Bot object
# Upon calling this function, TeleBot starts polling the Telegram servers for new messages.
# - interval: int (default 0) - The interval between polling requests
# - timeout: integer (default 20) - Timeout in seconds for long polling.
# - allowed_updates: List of Strings (default None) - List of update types to request
tb . infinity_polling ( interval = 0 , timeout = 20 )
# getMe
user = tb . get_me ()
# setWebhook
tb . set_webhook ( url = "http://example.com" , certificate = open ( 'mycert.pem' ))
# unset webhook
tb . remove_webhook ()
# getUpdates
updates = tb . get_updates ()
# or
updates = tb . get_updates ( 1234 , 100 , 20 ) #get_Updates(offset, limit, timeout):
# sendMessage
tb . send_message ( chat_id , text )
# editMessageText
tb . edit_message_text ( new_text , chat_id , message_id )
# forwardMessage
tb . forward_message ( to_chat_id , from_chat_id , message_id )
# All send_xyz functions which can take a file as an argument, can also take a file_id instead of a file.
# sendPhoto
photo = open ( '/tmp/photo.png' , 'rb' )
tb . send_photo ( chat_id , photo )
tb . send_photo ( chat_id , "FILEID" )
# sendAudio
audio = open ( '/tmp/audio.mp3' , 'rb' )
tb . send_audio ( chat_id , audio )
tb . send_audio ( chat_id , "FILEID" )
## sendAudio with duration, performer and title.
tb . send_audio ( CHAT_ID , file_data , 1 , 'eternnoir' , 'pyTelegram' )
# sendVoice
voice = open ( '/tmp/voice.ogg' , 'rb' )
tb . send_voice ( chat_id , voice )
tb . send_voice ( chat_id , "FILEID" )
# sendDocument
doc = open ( '/tmp/file.txt' , 'rb' )
tb . send_document ( chat_id , doc )
tb . send_document ( chat_id , "FILEID" )
# sendSticker
sti = open ( '/tmp/sti.webp' , 'rb' )
tb . send_sticker ( chat_id , sti )
tb . send_sticker ( chat_id , "FILEID" )
# sendVideo
video = open ( '/tmp/video.mp4' , 'rb' )
tb . send_video ( chat_id , video )
tb . send_video ( chat_id , "FILEID" )
# sendVideoNote
videonote = open ( '/tmp/videonote.mp4' , 'rb' )
tb . send_video_note ( chat_id , videonote )
tb . send_video_note ( chat_id , "FILEID" )
# sendLocation
tb . send_location ( chat_id , lat , lon )
# sendChatAction
# action_string can be one of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video',
# 'record_audio', 'upload_audio', 'upload_document' or 'find_location'.
tb . send_chat_action ( chat_id , action_string )
# getFile
# Downloading a file is straightforward
# Returns a File object
import requests
file_info = tb . get_file ( file_id )
file = requests . get ( 'https://api.telegram.org/file/bot{0}/{1}' . format ( API_TOKEN , file_info . file_path ))
テレボットのすべてのsend_xyz関数は、オプションのreply_markup引数を取得します。この引数は、 ReplyKeyboardMarkup 、 ReplyKeyboardRemove 、またはForceReplyのインスタンスでなければなりません。これらは型で定義されています。
from telebot import types
# Using the ReplyKeyboardMarkup class
# It's constructor can take the following optional arguments:
# - resize_keyboard: True/False (default False)
# - one_time_keyboard: True/False (default False)
# - selective: True/False (default False)
# - row_width: integer (default 3)
# row_width is used in combination with the add() function.
# It defines how many buttons are fit on each row before continuing on the next row.
markup = types . ReplyKeyboardMarkup ( row_width = 2 )
itembtn1 = types . KeyboardButton ( 'a' )
itembtn2 = types . KeyboardButton ( 'v' )
itembtn3 = types . KeyboardButton ( 'd' )
markup . add ( itembtn1 , itembtn2 , itembtn3 )
tb . send_message ( chat_id , "Choose one letter:" , reply_markup = markup )
# or add KeyboardButton one row at a time:
markup = types . ReplyKeyboardMarkup ()
itembtna = types . KeyboardButton ( 'a' )
itembtnv = types . KeyboardButton ( 'v' )
itembtnc = types . KeyboardButton ( 'c' )
itembtnd = types . KeyboardButton ( 'd' )
itembtne = types . KeyboardButton ( 'e' )
markup . row ( itembtna , itembtnv )
markup . row ( itembtnc , itembtnd , itembtne )
tb . send_message ( chat_id , "Choose one letter:" , reply_markup = markup )最後の例では、この結果が得られます。
# ReplyKeyboardRemove: hides a previously sent ReplyKeyboardMarkup
# Takes an optional selective argument (True/False, default False)
markup = types . ReplyKeyboardRemove ( selective = False )
tb . send_message ( chat_id , message , reply_markup = markup ) # ForceReply: forces a user to reply to a message
# Takes an optional selective argument (True/False, default False)
markup = types . ForceReply ( selective = False )
tb . send_message ( chat_id , "Send me another word:" , reply_markup = markup )強制的に:
このオブジェクトは、テキストメッセージ内の1つの特別なエンティティを表します。たとえば、ハッシュタグ、ユーザー名、URLなど。属性:
typeurloffsetlengthuser例はmessage.entities[num].<attribute>
ここでnum返信/メッセージに複数のエンティティがある場合は、回答のエンティティ番号またはエンティティの順序です。
message.entitiesエンティティオブジェクトのリストを返します。
message.entities[0].type最初のエンティティのタイプを与えます
詳細については、Bot APIを参照してください
ボットAPIのバージョン5.0以降、独自のローカルボットAPIサーバーを実行する可能性があります。 Pytelegrambotapiもこの機能をサポートしています。
from telebot import apihelper
apihelper . API_URL = "http://localhost:4200/bot{0}/{1}"重要:ここに記載されているように、ローカルAPIサーバーに切り替える前に、Telegramサーバーからボットをログアウトする必要があります。 pytelegrambotapiでbot.log_out()を使用します
注:4200はポートの例です
新規:テレボットの非同期実装があります。この動作を有効にするには、テレボットの代わりに非同期のインスタンスを作成します。
tb = telebot . AsyncTeleBot ( "TOKEN" )これで、Telegram APIを呼び出すすべての関数は、別の非同期タスクで実行されます。 asynctelebotを使用すると、次のことを行うことができます。
import telebot
tb = telebot . AsyncTeleBot ( "TOKEN" )
@ tb . message_handler ( commands = [ 'start' ])
async def start_message ( message ):
await bot . send_message ( message . chat . id , 'Hello!' )例をご覧ください
5000文字を超えるメッセージを送信する必要がある場合があります。 Telegram APIは、1つのリクエストでその多くの文字を処理できないため、メッセージを複数で分割する必要があります。 APIを使用してそれを行う方法は次のとおりです。
from telebot import util
large_text = open ( "large_text.txt" , "rb" ). read ()
# Split the text each 3000 characters.
# split_string returns a list with the splitted text.
splitted_text = util . split_string ( large_text , 3000 )
for text in splitted_text :
tb . send_message ( chat_id , text )または、新しいsmart_split関数を使用して、より意味のあるサブストリングを取得できます。
from telebot import util
large_text = open ( "large_text.txt" , "rb" ). read ()
# Splits one string into multiple strings, with a maximum amount of `chars_per_string` (max. 4096)
# Splits by last 'n', '. ' or ' ' in exactly this priority.
# smart_split returns a list with the splitted text.
splitted_text = util . smart_split ( large_text , chars_per_string = 3000 )
for text in splitted_text :
tb . send_message ( chat_id , text )テレボットコンストラクターは、次のオプションの引数を取ります。
メッセージハンドラーの代替として、テレボットのリスナーとして関数を登録することもできます。
注意:ハンドラーは消えません!メッセージは、ハンドラーとリスナーの両方によって処理されます。また、スレッドのために最初に機能するものを予測することは不可能です。スレッド= falseを使用すると、ハンドラーが呼び出された後、カスタムリスナーは早めに動作します。例:
def handle_messages ( messages ):
for message in messages :
# Do something with the message
bot . reply_to ( message , 'Hi' )
bot . set_update_listener ( handle_messages )
bot . infinity_polling ()Webhooks Telegramを使用する場合、通話ごとに1つの更新を送信します。処理するには、Process_new_messages([update.message])を受信するときに呼び出す必要があります。
examples/webhook_examplesディレクトリにWebhooksを使用した例がいくつかあります。
Telebot Module Loggerを使用して、テレボットに関するデバッグ情報を記録できます。 telebot.loggerを使用して、テレボットモジュールのロガーを取得します。ロガーにカスタムロギングハンドラーを追加することができます。詳細については、Pythonロギングモジュールページを参照してください。
import logging
logger = telebot . logger
telebot . logger . setLevel ( logging . DEBUG ) # Outputs debug messages to console.同期の場合:
リクエストにはプロキシを使用できます。 apihelper.proxyオブジェクトは、コールrequestsプロキシ引数によって使用されます。
from telebot import apihelper
apihelper . proxy = { 'http' : 'http://127.0.0.1:3128' } socket5プロキシを使用する場合は、依存関係pip install requests[socks]をインストールする必要があり、 gunicorn 、 PySocks 、 pyTelegramBotAPI 、 requests 、 urllib3の最新バージョンがあることを確認してください。
apihelper . proxy = { 'https' : 'socks5://userproxy:password@proxy_address:port' }asyncの場合:
from telebot import asyncio_helper
asyncio_helper . proxy = 'http://127.0.0.1:3128' #url使用することにより、Real Telegramサーバーとの相互作用を無効または変更できます
apihelper . CUSTOM_REQUEST_SENDER = your_handlerパラメーター。 Requests.Requestの代わりに呼び出される独自の機能を渡すことができます。
例えば:
def custom_sender ( method , url , ** kwargs ):
print ( "custom_sender. method: {}, url: {}, params: {}" . format ( method , url , kwargs . get ( "params" )))
result = util . CustomRequestResponse ( '{"ok":true,"result":{"message_id": 1, "date": 1, "chat": {"id": 1, "type": "private"}}}' )
return result次に、APIを使用して、ハンドラーコードでリクエストを続行できます。
apihelper . CUSTOM_REQUEST_SENDER = custom_sender
tb = TeleBot ( "test" )
res = tb . send_message ( 123 , "Test" )結果は次のとおりです。
custom_sender. method: post, url: https://api.telegram.org/botololo/sendMessage, params: {'chat_id': '123', 'text': 'Test'}
テレボットの完全に非同期バージョンがあります。このクラスはスレッドで制御されていません。 Asyncioタスクは、すべてのものを実行するために作成されます。
asynctelebotのエコーボットの例:
# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.
from telebot . async_telebot import AsyncTeleBot
import asyncio
bot = AsyncTeleBot ( 'TOKEN' )
# Handle '/start' and '/help'
@ bot . message_handler ( commands = [ 'help' , 'start' ])
async def send_welcome ( message ):
await bot . reply_to ( message , """
Hi there, I am EchoBot.
I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!
""" )
# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
@ bot . message_handler ( func = lambda message : True )
async def echo_message ( message ):
await bot . reply_to ( message , message . text )
asyncio . run ( bot . polling ())ここで見ることができるように、キーワードは待っています。
非同期タスクはプロセッサのパフォーマンスに依存します。多くの非同期タスクは並行して実行できますが、スレッドタスクは互いにブロックされます。
Asynctelebotは非同期です。リクエストモジュールの代わりにAIOHTTPを使用します。
私たちの例フォルダーのより多くの例を参照してください
Telegram Bot APIは、message.chatの新しいタイプチャットをサポートしています。
Chatオブジェクトのtype属性を確認します。 if message . chat . type == "private" :
# private chat message
if message . chat . type == "group" :
# group chat message
if message . chat . type == "supergroup" :
# supergroup chat message
if message . chat . type == "channel" :
# channel message長い間アイドル状態であったボットインスタンスは、最後に使用されているセッションのタイムアウトのためにメッセージを送信するときにサーバーによって拒否される可能性があります。 apihelper.SESSION_TIME_TO_LIVE = 5 * 60初期化に追加して、アクティビティなしで5分後にレクリエーションを強制します。
助けを得る。話し合う。チャット。
ニュースチャンネルに参加してください。ここでは、リリースと更新を投稿します。
テンプレートは、基本プロジェクトのアーキテクチャを含む準備ができたフォルダーです。テンプレートの例をいくつか紹介します。
ここにボットをリストしたいですか?プルリクエストを行うだけです。パブリックソースコードを備えたボットのみが受け入れられます。