python-3.x - 从 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中找到我的完整代码
我的代码是
- “Learning Scrapy”一书中的延迟扩展https://github.com/scalingexcellence/scrapybook/blob/master/ch09/properties/properties/latencies.py
- python-telegram-bot 库中的 echobot 示例https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py
- 关于统计数据收集的官方 scrapy 文档https://docs.scrapy.org/en/latest/topics/stats.html
解决方案
调用updater.stop()
肯定会停止机器人。从 的文档中python-telegram-bot
,
"""Stops the polling/webhook thread, the dispatcher and the job queue."""
检查是否updater.stop()
在蜘蛛关闭后调用。机器人可能不会立即停止,但最终会停止。
推荐阅读
- ios - [__NSCFString objectForKey:]:文本字段搜索崩溃
- reactive-programming - Spring WebFlux/ 反应堆核心
- jquery - Angular 7上的引导程序出现错误,因为'JQuery类型上不存在属性折叠
` - cluster-analysis - 单个“多输入 Tx”与多个“单输入 Tx”
- git - 在本地撤消 git rebase 跳过
- dart - 如何处理可扩展表单上的控制器 TextField
- c# - 试图从 SQL Server Profiler 获取过程名称,而是显示“sp_reset_connection”
- php - AWS SDK PHP - 如何通过一个链接加载多个文件?如何创建一个 zip 文件?
- java - 如何创建从 Activity 底部绘制的 listView?
- batch-file - 在没有管理员权限的情况下在特定位置打开 cmd 的 .bat 文件