[英]How to find the 𝘯th message in telegram with the python-telegram-bot API?
[英]Getting one message using the telegram python API?
我想創建一個電報機器人,在看到命令 /define 后,它會詢問這個詞。 我想在機器人請求后提取用戶發送的單詞。 我該怎么做?
import telegram
from telegram.ext import Updater
from telegram.ext import MessageHandler, Filters
from telegram.ext import CommandHandler
updater = Updater(token='******************')
dispatcher = updater.dispatcher
def define(bot, update):
bot.send_message(chat_id=update.message.chat_id, text="Enter word")
word = '''get content of following message'''
definition = get_definition(word)
bot.send_message(chat_id=update.message.chat_id, text=definiton)
definition_handler = CommandHandler('define', define)
dispatcher.add_handler(definition_handler)
updater.start_polling()
實際上,令牌是您創建任何您想要的機器人所需的唯一東西。 像你這樣的機器人代碼應該遵循相同的邏輯結構:
# -*- coding: utf-8 -*-
import telebot # importing pyTelegramBotAPI library
import time
import sys
bot = telebot.Telebot(token='YOUR API TOKEN') # supply your future bot with the token you have received
@bot.message_handler(commands=['define', 'Define'])
def echo_msg(message):
echo = bot.send_message(chat_id=message.chat.it,
text='What word would you want me to extract, sir?')
bot.register_next_step_handler(message=echo, callback=extract_msg)
def extract_msg(message):
msg.append(message.text)
print(msg)
def main_loop():
bot.polling(none_stop=True)
while True:
time.sleep(1)
if __name__ == '__main__':
try:
main_loop()
except KeyboardInterrupt:
print(sys.stderr '\nExiting by user request'\n')
sys.exit(0)
好的,每個機器人都需要一個message_handler
來處理傳入的信息。
在您的情況下,它是一個命令,可觸發機器人要求將單詞提取到列表中。 如果你沒有定義bot.register_next_step_handler()
,這個命令根本不會做任何動作(除了它要求輸入一個詞的事實)。
函數extract_msg()
附加用戶編寫的下一個單詞並將msg
列表打印到您的控制台中。
函數main_loop()
運行機器人直到暫停,並在每個單詞提取后使其空閑一秒鍾。 要停止機器人,請按Ctrl + C。
我希望這就足夠了。 下一步是跟蹤輸入/define
或/Define
並提取他/她的詞請求。 此外,最好使msg
list 更具描述性,或者實現完全不同的提取方法。 這只是提供信息,在實踐中幾乎不適用。
我在調用 stderr 時修復了一個錯誤:
# -*- coding: utf-8 -*-
import telebot # importing pyTelegramBotAPI library
import time
import sys
bot = telebot.Telebot(token='YOUR API TOKEN') # supply your future bot with the token you have received
@bot.message_handler(commands=['define', 'Define'])
def echo_msg(message):
echo = bot.send_message(chat_id=message.chat.it,
text='What word would you want me to extract, sir?')
bot.register_next_step_handler(message=echo, callback=extract_msg)
def extract_msg(message):
msg.append(message.text)
print(msg)
def main_loop():
bot.polling(none_stop=True)
while True:
time.sleep(1)
if __name__ == '__main__': try:
main_loop() except KeyboardInterrupt:
print(sys.stderr('\nExiting by user request'\n'))
sys.exit(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.