Python IRC 机器人链接解析器?

1 投票
1 回答
518 浏览
提问于 2025-04-18 13:48

我在这个话题上找不到很多信息,但我想要一个例子,来说明当某个链接被发到IRC频道时,如何处理这个链接。有没有什么建议或者例子呢?

1 个回答

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

免责声明: 我是circuits的开发者

更新: 已测试,工作正常。

撰写回答