【问题标题】:Python IRC Bot link resolver?Python IRC Bot链接解析器?
【发布时间】:2014-09-09 03:35:45
【问题描述】:

所以我无法找到有关该主题的大量信息,但我正在寻找一个示例来解决将给定链接发布到 IRC 频道时的链接。任何提示/示例?

【问题讨论】:

  • 你的意思是得到它的标题等? ircbot.py 是一个很好的起点(免责声明:我是开发者)
  • 是的。此外,我已经为机器人编程了框架,但我只是在寻找有关获取标题并将它们传递到频道的建议,以便您在点击链接之前了解链接是什么:P

标签: python hyperlink bots irc


【解决方案1】:

我写了一个简单的例子,完全符合你的要求。

请随意将其用作满足您需求的基础!

#!/usr/bin/env python

from re import findall

from circuits import Component
from circuits.ne t.events import connect
from circuits.net.sockets import TCPClient
from circuits.protocols.irc import ERR_NICKNAMEINUSE
from circuits.protocols.irc import RPL_ENDOFMOTD, ERR_NOMOTD
from circuits.protocols.irc import IRC, PRIVMSG, USER, NICK, JOIN

from requests import get
from lxml.html import fromstring


class Bot(Component):

    def init(self, host, port=6667):
        self.host = host
        self.port = port

        TCPClient().register(self)
        IRC().register(self)

    def ready(self, component):
        self.fire(connect(self.host, self.port))

    def connected(self, host, port):
        self.fire(USER("circuits", host, host, "Test circuits IRC Bot"))
        self.fire(NICK("circuits"))

    def numeric(self, source, target, numeric, args, message):
        if numeric == ERR_NICKNAMEINUSE:
            self.fire(NICK("%s_" % args))
        if numeric in (RPL_ENDOFMOTD, ERR_NOMOTD):
            self.fire(JOIN("#circuits"))

    def message(self, source, target, message):
        if target[0] == "#":
            urls = findall("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", message)  # noqa
            if urls:
                url = urls[0]
                response = get(url)
                if response.status_code == 200:
                    doc = fromstring(response.text)
                    title = doc.cssselect("title")
                    if title:
                        title = title[0].text.strip()
                        self.fire(
                            PRIVMSG(
                                target,
                                "URL: {0:s} Title: {1:s}".format(
                                    url,
                                    title
                                )
                            )
                        )
        else:
            self.fire(PRIVMSG(source[0], message))


bot = Bot("irc.freenode.net")

bot.run()

你需要:

您可以通过以下方式安装这些:

pip install circuits cssselect lxml requests

免责声明:我是电路开发者

更新:经测试可按预期工作。

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 2012-10-15
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    相关资源
    最近更新 更多