识别发送用户,Python IRC

时间:2015-06-22 20:42:06

标签: python bots irc twitch

所以我为自己的频道制作了一个Twitch.tv机器人,稍微玩了一下后,我想让某些用户有一些命令限制,有些命令可以说用户名,例如: / p>

Username reply example:

Person1: !tea
PythonBot: Would you like some tea, Person1?

Admin restriction example:

Person1: !ban Person2
PythonBot: I'm sorry, Person1, This command is restricted to admins only.

好的,所以这是我正在使用的代码(我将尽快修改它以使其成为我自己的代码)

import socket
import threading



bot_owner = '~Not Today~'
nick = '~Not Today~'
channel = '~Not Today~'
server = 'irc.twitch.tv'
password = '~Not Today~'

queue = 13

irc = socket.socket()
irc.connect((server, 6667))

irc.send('PASS ' + password + '\r\n')
irc.send('USER ' + nick + ' 0 * :' + bot_owner + '\r\n')
irc.send('NICK ' + nick + '\r\n')
irc.send('JOIN ' + channel + '\r\n')

def message(msg):
    global queue
    queue = 5
    if queue < 20:
        irc.send('PRIVMSG' + channel + ' :' + msg + '\r\n')
    else:
        print 'Message Deleted'

def queuetimer():
    global queue
    queue = 0
    threading.Timer(30,queuetimer).start()
queuetimer()

while True:
    botdata = irc.recv(1204)
    botuser = botdata.split(':')[1]
    botuser = botuser.split('!')[0]
    print botdata

    if botdata.find('PING') != -1:
        irc.send(botdata.replace('PING', 'PONG'))
    if botdata.find('!res') != -1:
        irc.send(botdata.replace('!res', '1600x900'))

1 个答案:

答案 0 :(得分:1)

抽搐的IRC原始信息就像

  

:jkm!jkm@jkm.tmi.twitch.tv PRIVMSG #trumpsc:需要Kappa

对于上述消息,它实际上意味着用户jkm在频道trumpscneeds Kappa

对于您的代码,获取botuser的方法是正确的,但您没有收到用户发送的消息,请添加以下代码以获取消息

botmsg = botdata.split(':')[2]

所以你得到了消息和用户名,下一步就是处理它们。 以下是您需要的一些示例。对我来说,我会为其他命令准备一个adminuserListcommmandList,但我会在这里简化它。

def commmanHandler(botuser, botmsg):         # botmsg = '!ban user1'  
    command = botmsg.split(' ')[0]           # command = '!ban'
    command = command[1:]                    # command = 'ban'
    argu = message.split(' ')[1]             # argu = 'user1' 

    if command not in commmandList:         
        raise Exception("command not support")

    if command == 'ban':                     # ban command, or using switch
        # check if admin
        if botuser not in adminList:
            raise Exception("I'm sorry, " + botuser + ", This command is restricted to admins only.")
        # admin, able to ban
        irc.send('PRIVMSG' + channel + ' :' + '.ban ' + argu)

然后在while循环中调用此函数来处理所有消息

try:
    commmanHandler(botuser, botmsg)
except Exception, e:
    print e
    irc.send('PRIVMSG' + channel + ' :' + e)

这将是我的解决方案,而且,不要忘记授予机器人主持人权限。