首页 > 解决方案 > 从 Scrapy 获取统计信息的 Python Telegram 机器人

问题描述

我想编写一个 Telegram 机器人,它可以根据要求提供 Scrapy 统计信息。我的尝试大多有效,唯一的问题是强行关闭蜘蛛(显然)不会阻止机器人。

所以我有两个问题:

这是相关的类:

class TelegramBot(object):
    telegram_token = telegram_credentials.token

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def __init__(self, crawler):
        self.crawler = crawler

        cs = crawler.signals
        cs.connect(self._spider_closed, signal=signals.spider_closed)

        """Start the bot."""
        # Create the Updater and pass it your bot's token.
        # Make sure to set use_context=True to use the new context based callbacks
        # Post version 12 this will no longer be necessary
        self.updater = Updater(self.telegram_token, use_context=True)

        # Get the dispatcher to register handlers
        dp = self.updater.dispatcher

        # on different commands - answer in Telegram
        dp.add_handler(CommandHandler("stats", self.stats))

        # Start the Bot
        self.updater.start_polling()

    def _spider_closed(self, spider, reason):
        # Stop the Bot
        self.updater.stop()

    def stats(self, update, context):
        # Send a message with the stats
        msg = (
            "Spider "
            + self.crawler.spider.name
            + " stats: "
            + str(self.crawler.stats.get_stats())
        )

        update.message.reply_text(msg)

在这里,您可以在 Scrapy 教程引用蜘蛛https://github.com/jtommi/scrapy_telegram-bot_example/blob/master/tutorial/tutorial/telegram-bot.py中找到我的完整代码

我的代码是

标签: python-3.xscrapytwistedpython-telegram-bot

解决方案


调用updater.stop()肯定会停止机器人。从 的文档中python-telegram-bot

 """Stops the polling/webhook thread, the dispatcher and the job queue."""

检查是否updater.stop()在蜘蛛关闭后调用。机器人可能不会立即停止,但最终会停止。


推荐阅读