2

我一直在尝试编写 IRC 机器人,而我已经成功了。我在执行我想做的事情时遇到问题。代码工作正常,但我有以下问题:

因为当我使用 time.sleep(seconds) 添加第二个 While 时,机器人使用 While 循环从 IRC 读取命令,所以机器人无法连接,因为它读取了我的第二个循环并暂停连接以不及时响应:PING这样做会断开连接。我一直在搜索,但越是搜索越让我感到困惑,因为我不知道我应该尝试什么。

无堆栈,多线程,子进程。有这么多的结果,我只是变得更加困惑。那么我正在尝试 RSS 机器人的最佳方法是什么,如果我在 IRC 频道中使用命令 !rss,机器人工作正常,但我需要它每 10 分钟检查一次新的,如果使用睡眠命令,主循环会混乱向上。

这是我的代码:

#!/usr/bin/python

import socket, sys, string, time, feedparser, hashlib
port = 6667
nick = "RSSbot"
host = 'irc.server.com'
name =  "RSSBOT"
channel = '#debug'
ident = 'rssbot'
irc = socket.socket()
irc.connect ( (host, port) )
irc.send ( 'NICK ' + nick + '\r\n' )
irc.send ( 'USER ' + ident + ' ' +  ident + ' ' + ident + ' :rssbot\r\n' )

def readRss():
    feedurl = feedparser.parse("http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=username")
    newest = feedurl['items'][0].title
    newest = newest.replace("username:","")
    msg = newest.split("http://")
    title = msg[0]
    url = msg[1]
    url = "http://" + url
    e = feedurl.entries[2]
    threadurl = e.link
    id = hashlib.md5(url + title).hexdigest()
    irc.send ("PRIVMSG #debug :Tittle:%s\r\n" % newest)
    irc.send ("PRIVMSG #debug :URL: %s\r\n" % url)
    irc.send ("PRIVMSG #debug :MD5: %s\r\n" % id)
while 1:
    data = irc.recv ( 1024 )
    print(data)

    if data.find ( '376' ) != -1:
        irc.send( 'JOIN ' + channel + '\r\n' )
    if data.find ( 'PING' ) != -1:
        irc.send( 'PONG ' + data.split() [1] + '\r\n')
    if data.find ( '!rss' ) != -1:
        feedurl = feedparser.parse("http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=username")
        newest = feedurl['items'][0].title
        newest = newest.replace("username:","")
        msg = newest.split("http://")
        title = msg[0]
        url = msg[1]
        url = "http://" + url
        #e = feedurl.entries[2]
        #threadurl = e.link
        id = hashlib.md5(url + title).hexdigest()
        irc.send ("PRIVMSG #debug :Tittle:%s\r\n" % newest)
        irc.send ("PRIVMSG #debug :URL: %s\r\n" % url)
        irc.send ("PRIVMSG #debug :MD5: %s\r\n" % id)
    while true:
        readRss()
        time.sleep(300)

如果我在 while 1: 中添加一个 while :true 和 time.sleep(300),则 sleep 命令与 while 1: 循环冲突,我需要做类似的事情,这样我就可以每 x 分钟检查一次新的提要。我能做什么?

4

2 回答 2

3

而不是一个新的循环,使用一个单独的计时器。

import time
last_update = time.time()

while 1:
   # the rest of your while loop as usual
   now = time.time()
   if now - last_update > 300:
       # you've waited 300 seconds
       # check feeds or whatever 
       last_update = now
于 2012-04-06T15:05:49.007 回答
0

我用我的 irc 机器人上的线程模块处理了这个问题 检查项目这可能会对你有所帮助https://github.com/mouuff/MouBot(我调用了函数 ircloop 这将回答服务器 ping 并做机器人工作:)

于 2012-10-13T20:52:07.117 回答