我一直在尝试编写 IRC 机器人,但我已经成功了。我在执行我想做的事情时遇到问题。代码工作正常,但我有以下问题:
由于机器人使用 While 循环从 IRC 读取命令,当我添加第二个 While 和 time.sleep(seconds) 时,机器人不会连接,因为它读取我的第二个循环并暂停连接,没有及时响应:PING 会断开连接。我一直在寻找,但搜索得越多,我就越困惑,因为我不知道我应该尝试什么。
无堆栈、多线程、子进程。结果太多了,让我更加困惑。那么我正在尝试 RSS 机器人的最佳方法是什么,如果我在 IRC channel 中使用命令 !rss,机器人可以正常工作,但我需要它每 10 分钟检查一次新命令,如果使用 sleep 命令,主循环会变得困惑向上。
这是我的代码:
#!/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 分钟检查一次新的提要。我能做什么?
最佳答案
使用单独的计时器,而不是新的循环。
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
关于python - IRC 机器人使循环休眠而不中断主循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10045261/