Создание команд !addcom и !delcom на twitch irc-боте. Перейти через строку кода

Я создаю бота для чата и пытаюсь создать команды !addcom и !delcom для создания и удаления команд через чат. И дело в том, что почти одна и та же строка кода работает для одной команды и не работает для другой. Я тестировал с отпечатками и разрывами, и похоже, что он просто перепрыгивает через них.

Строка, которую он просто перепрыгивает:

if globalcommands.has_key(commanddel):
                    sendMessage(irc, channel, user + " you can't add a command called " + '"!' + commanddel + '" !!!')
                    break

А вот и полный код:

import string
import json
from Socket import openSocket, sendMessage
from Initialize import joinRoom
from Read import getUser, getMessage, getChannel, string_1, string_2_plus

irc = openSocket()
joinRoom(irc)
readbuffer = ""
irc.send("CAP REQ :twitch.tv/membership\r\n")
irc.send("CAP REQ :twitch.tv/commands\r\n")

try:
    with file("commands.json","r") as commandsDatabase:
        commands = json.load(commandsDatabase)
except IOError:
    commands = {}
    with file("commands.json","w") as commandsDatabase:
        json.dump(commands, commandsDatabase)

globalcommands = {"addcom": True, "delcom": True, "spank": True}

while True:
    readbuffer = readbuffer + irc.recv(1024)
    temp = string.split(readbuffer, "\n")
    readbuffer = temp.pop()

    for line in temp:
###Essenciais###--------------------------------------------------------------------------------------------------------------------------------------------
#Mostra a linha que e dada pelo servidor de IRC (So pelo sim pelo nao).-----------------------------------------------------------------------
        print (line)
#---------------------------------------------------------------------------------------------------------------------------------------------
#Impede que seja desconectado pelo servidor de IRC.-------------------------------------------------------------------------------------------
        if line.startswith('PING'):
            irc.send('PONG ' + line.split( ) [ 1 ] + '\r\n')
            print "PONGED BACK"
            break
#---------------------------------------------------------------------------------------------------------------------------------------------
#Le a linha que e dada pelo servidor de IRC e devevole o utilizador, a menssagem e o canal. Volta se algum for nulo.--------------------------
        user = getUser(line)
        message = getMessage(line)
        channel = getChannel(line)
        if channel == None or user == None or message == None:
            break
#---------------------------------------------------------------------------------------------------------------------------------------------
#Random Strings.------------------------------------------------------------------------------------------------------------------------------
        stringspace = " "
        nothing = ""
#---------------------------------------------------------------------------------------------------------------------------------------------
#Formata o texto e mostra mostra na consola.--------------------------------------------------------------------------------------------------
        print channel + ": " + user + " > " + message
#---------------------------------------------------------------------------------------------------------------------------------------------
###Essenciais END###----------------------------------------------------------------------------------------------------------------------------------------

        if message.startswith("!addcom "):
            if message.count(stringspace) >= 2:
                try:
                    commandadd = string_1(message)
                    answer = string_2_plus(message)
                except IndexError:
                    sendMessage(irc, channel, user + " the command is used this way !addcom !<command_name> <command_answer>")
                    break
                if globalcommands.has_key(commandadd):
                    sendMessage(irc, channel, user + " you can't add a command called " + '"!' + commandadd + '" !!!')
                    break
                try:
                    commands[commandadd]
                except KeyError:
                    commands[commandadd] = answer
                    sendMessage(irc, channel, user + " the command !" + commandadd + " has been added!!!")
                    with file("commands.json","w") as commandsDatabase:
                        json.dump(commands, commandsDatabase)
                    break
                sendMessage(irc, channel, user + " the command you tried to add alredy exists!!!")
                break
            sendMessage(irc, channel, user + " the command is used this way !addcom !<command_name> <command_answer>")
            break

        if message.startswith("!delcom "):
            if message.count(stringspace) == 1:
                try:
                    commanddel = string_1(message)
                except IndexError:
                    sendMessage(irc, channel, user + "the command is used this way !delcom !<command_name>")
                    break
                if globalcommands.has_key(commanddel):
                    sendMessage(irc, channel, user + " you can't add a command called " + '"!' + commanddel + '" !!!')
                    break
                try:
                    commands[commanddel]
                except KeyError:
                    sendMessage(irc, channel, user + " the command you tried to delete doens't exist!!!")
                    break
                del commands[commanddel]
                sendMessage(irc, channel, user + " the command !" + commanddel + " has been deleted!!!")
                with file("commands.json","w") as commandsDatabase:
                    json.dump(commands, commandsDatabase)
                break
            sendMessage(irc, channel, user + " the command is used this way !delcom !<command_name>")
            break

Если вам нужно посмотреть какие-либо другие файлы здесь, у вас есть мой репозиторий github: https://github.com/BlasterJoni/ClientSideTwitchChatBotPython/


person João Arvana    schedule 29.01.2016    source источник
comment
Использование break остановит цикл while   -  person ZetaRift    schedule 30.01.2016
comment
Это предназначено, но все равно спасибо за ваш комментарий. Я уже понял, что это неправильное определение вещей. Забыл, что в конце строки стоит \r xD   -  person João Arvana    schedule 30.01.2016


Ответы (1)


Я уже понял, что не правильно определяю вещи. Я забыл, что в конце строки есть \r.

Я определил два разных способа получения строки1 из сообщения: один для !addcom и один для !delcom.

Мне просто нужно было определить !delcom следующим образом:

def string_1(message):
string1 = message.split("!", 2)[2].split("\r", 1)[0]
return string1

и он начал работать.

person João Arvana    schedule 29.01.2016