【问题标题】:Python IRC Bot: Set variables from channel readingPython IRC Bot:从频道读取中设置变量
【发布时间】:2015-11-24 03:11:42
【问题描述】:

我正在开发一个简单的 IRC 机器人,我正在尝试创建一个计时器高亮功能。

当我输入以下内容时:

!hl 10

我想在 分钟 内将 10(或任何可能存在的位置)分配为名为“var_time”的变量。

var_time= 0 #External statement

def timer_commands(nick,channel,message):
       global var_time
       if message.find("!hl", var_time )!=-1:
           ircsock.send('PRIVMSG %s :%s I will highlight you in %s minutes!\r\n' % (channel,nick, var_time))
           time.sleep(float(var_time)) #The delay here is in seconds
           ircsock.send('PRIVMSG %s :%s, You asked me %s minutes ago to highlight you.!\r\n' % (channel,nick,var_time))

我知道 var_time 没有取值 10,这正是我的问题,我怎样才能做到这一点?

下面是函数的调用方式:

  while 1:
      ircmsg = ircsock.recv(2048) # receive data from the server
      ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
      ircraw = ircmsg.split(' ')
      print(ircmsg) # Here we print what's coming from the server

      if ircmsg.find(' PRIVMSG ')!=-1:
         nick=ircmsg.split('!')[0][1:]
         channel=ircmsg.split(' PRIVMSG ')[-1].split(':')[0]
         timer_commands(nick,channel,ircmsg)

提前致谢。

解决方案:

  def timer_commands(nick,channel,message):
      if ircraw[3] == ':!hl':
         var_time = float(ircraw[4])
         ircsock.send('PRIVMSG %s :I will highlight you in %s minutes!\r\n' % (channel, nick, ircraw[4]))
         time.sleep(var_time*60) #Delay in Minutes
         ircsock.send('PRIVMSG %s :%s pYou asked me %s minutes ago to highlight you.! \r\n' % (channel, nick, ircraw[4]))

谢谢匿名

【问题讨论】:

    标签: python sockets bots irc timedelay


    【解决方案1】:

    尝试正则表达式:

    >>> re.match('!hl ([0-9]+)$', '!hl 91445569').groups()[0]
    '91445569'
    >>> re.match('!hl ([0-9]+)$', '!hl 1').groups()[0]
    '1'
    

    或者,在您的代码中:

    import re
    m = re.match('!hl ([0-9]+)$', ircmsg)
    if m is not None:
        var_time = int(re.groups()[0])
    

    【讨论】:

    • 感谢您的回答。我不熟悉 re 模块,但从你的例子来看,它似乎解决了我的问题。但是,当我将它放入我的代码 (pastebin.com/8VKM4eta) 时,我注意到“m”总是返回 None。
    • 好吧,这显然取决于“ircmsg”的值是多少。对于您的示例 (!hl 10),它可以工作
    猜你喜欢
    • 1970-01-01
    • 2011-10-05
    • 2015-03-23
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 2018-02-21
    • 2013-01-16
    相关资源
    最近更新 更多