【问题标题】:Getting one message using the telegram python API?使用电报 python API 获取一条消息?
【发布时间】:2017-06-30 17:12:50
【问题描述】:
我想创建一个电报机器人,在看到命令 /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()
【问题讨论】:
标签:
python
python-telegram-bot
【解决方案1】:
实际上,令牌是您创建所需的任何机器人所需的唯一东西。像你这样的机器人的代码应该遵循相同的逻辑结构:
# -*- 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 列表更具描述性,或者实现完全不同的提取方法。这只是提供信息,在实践中几乎不适用。
【解决方案2】:
我在调用 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)