gpt4 book ai didi

python : Check if IRC connection is lost (PING PONG? )

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:39 25 4
gpt4 key购买 nike

所以我的问题是,如果有 PING,我如何让我的机器人收听,如果在一分钟的时间间隔内没有 ping,它会使用react,就好像连接已经丢失一样。怎么做到这一点?

编辑:

这是注册连接失败的工作代码(尽管在重新连接时遇到问题):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import socket
import string
import os
import platform
import time

# Variables
HOST = "irc.channel.net"
PORT = 6667
NICK = "Botname"
IDENT = "Botname"
REALNAME = os.getenv('USER')
CHAN = "##ChannelName"
readbuffer = ""

# Our IRC connection
irc = socket.socket()
irc.settimeout(300)
connected = False
def connection(host, port, nick, ident, realname, chan):
while connected is False:
try:
irc.connect((host, port))
irc.send("NICK %s\r\n" % nick)
irc.send("USER %s %s bla :%s\r\n" % (ident, host, realname))
irc.send("JOIN :%s\r\n" % chan)
# Initial msg to send when bot connects
irc.send("PRIVMSG %s :%s\r\n" % (chan, "TehBot: "+ nick + " Realname: " + realname + " ."))
global connected
connected = True
except socket.error:
print "Attempting to connect..."
time.sleep(5)
continue
connection(HOST, PORT, NICK, IDENT, REALNAME, CHAN)

while connected:
try:
data = irc.recv ( 4096 )
# If connection is lost
if len(data) == 0:
break
print data
# If Nick is in use
if data.find ( "Nickname is already in use" ) != -1:
NICK = NICK + str(time.time())
connection(HOST, PORT, NICK, IDENT, REALNAME, CHAN)
# Ping Pong so we don't get disconnected
if data[0:4] == "PING":
irc.send ( "PONG " + data.split() [ 1 ] + "\r\n" )
except socket.timeout:
global connected
connected = False
print connected
break
print "Out of loop"
connection(HOST, PORT, NICK, IDENT, REALNAME, CHAN)

最佳答案

last_ping = time.time()
threshold = 5 * 60 # five minutes, make this whatever you want
while connected:
data = irc.recv ( 4096 )
# If Nick is in use
if data.find ( 'Nickname is already in use' ) != -1:
NICK = NICK + str(time.time())
Connection()
# Ping Pong so we don't get disconnected
if data.find ( 'PING' ) != -1:
irc.send ( 'PONG ' + data.split() [ 1 ] + '\r\n' )
last_ping = time.time()
if (time.time() - last_ping) > threshold:
break

这将在每次收到 ping 时记录时间,如果没有 ping 的时间太长,则跳出 connected 循环。您不需要 while connected == True:,只需 while connected: 做同样的事情。

此外,请考虑使用 connection 而不是 Connection,这是 Python 约定,仅对类使用大写名称。

关于 python : Check if IRC connection is lost (PING PONG? ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6853071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com