制作 Python IRC 机器人的正确方法是什么?
因此,我开始从头开始编写一个简单的程序化 Python IRC 机器人(即原始套接字),并且我正在尝试找出设计它的最佳方法。
通常我有一个很大的 while() 循环,它将坐在那里将从套接字接收到的数据推送到缓冲区中,我将使用大量的 if/else 语句来扫描字符串(使用正则表达式)来计算该怎么办?我有一种感觉,我不应该这样做,因为这感觉很糟糕。
我决定制作一本正则表达式及其相关含义的字典,例如
regexes = {"^PING: (.+)": "incomming_ping",
"more regex": "more meanings"}
,仅使用 for/in 循环来搜索文本并找出哪个正则表达式与其匹配。我已经走到这一步了,我想到的第一件事是“好吧,我可以让每个“过程”在特定的正则表达式匹配到函数时被调用,并根据含义调用适当的函数。我”我要么坚持使用大量的 if/else 语句,这是我一开始就不想做的,要么我可以使用某种 Python 的“eval”,这会立即敲响警钟,
不管怎样,我都被搞砸了 。 ,和我 的情况下想不出一种方法来解决这个问题(我目前不打算这样做,不要问为什么)。
在不完全面向对象
So I'm starting to write a simple procedural Python IRC bot from scratch (i.e. raw sockets) and I'm trying to work out the best way of designing it.
Usually I have a big ol' while() loop that'll sit there and push data received from the socket into a buffer and I'll use a massive if/else statement to scan through the string (using regular expressions) to work out what to do with it. I have a feeling that I shouldn't be doing that because it feels awful.
I decided to make a dictionary of regexes and their associated meanings, e.g.
regexes = {"^PING: (.+)": "incomming_ping",
"more regex": "more meanings"}
and just use a for/in loop to search through the text and find out which regex matches it. I've gotten this far, and I the first thing I thought was "okay, i can just make each 'procedure' to be called when a specific regex matches into a function, and call the appropriate function based on the meaning. I'm either stuck with using a massive if/else statement, which i didn't want to do in the first place, or I could use some sort of Pythonic 'eval', which immediately sets off alarm bells.
Either way I'm screwed, and I can't think of a way to approach this without going fully OOP (I don't plan on doing this at the moment, don't ask why).
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用函数引用代替字符串。
附注如果您“认真”对待 IRC 机器人,您可能想看看 Twisted。
Instead of strings, use references to functions.
ps. If you're "serious" about the IRC bot thing, you might want to have a look at Twisted.
编写一个通用的 IRC 协议解析器,它可以基于正则表达式。当命令遵循更通用的模式(
^[AZ]\s)时,为每个不同的命令(
^PING\s, ^PRIVMSG\s
)编写单独的正则表达式似乎有点多余)。然后,解析命令后,您可以使用 getattr(obj, 'irc_%s' % command) 查找执行该命令的方法/函数。
优点是您不需要维护所有方法以及每个命令都有一个模式的映射表。
这是Twisted 的 IRC 客户端:
Write a generic IRC protocol parser, which can be regexp-based. It seems a bit redundant to write a separate regexp for each distinct command (
^PING\s, ^PRIVMSG\s
), when commands follow a more general pattern (^[A-Z]\s
).Then, once you've parsed a command, you can lookup the method/function which perform that command by using
getattr(obj, 'irc_%s' % command)
.The advantage is that you don't need to maintain all your methods plus a mapping table with a pattern per command.
This is the technique used in Twisted's IRC client: