Я просто изучаю Python по мере необходимости, так что держись, потому что этот код будет грязным!...
Итак, я работал с Glade над созданием графического интерфейса для своего клиентского twitch irc чат-бота и создал эту кнопку-переключатель на панели инструментов:
<object class="GtkToggleToolButton" id="tool_deploy_toggle">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Connect</property>
<property name="use_underline">True</property>
<property name="stock_id">gtk-jump-to</property>
<signal name="toggled" handler="on_tool_deploy_toggle_toggled" swapped="no"/>
</object>
И я хочу, чтобы эта кнопка-переключатель открывала сокет и развертывала бота в twitch irc-чате, когда кнопка переключается «вниз» (а также выполняла некоторые определения и загрузку, как вы можете видеть):
irc = botOpenSocket()
joinRoom(irc)
readbuffer = ""
irc.send("CAP REQ :twitch.tv/membership\r\n")
irc.send("CAP REQ :twitch.tv/commands\r\n")
irc.send("CAP REQ :twitch.tv/tags\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 = {"spank": True}
moderatorcommands = {"addcom": True, "delcom": True}
stringspace = " "
nothing = ""
now = time.time()
cooldown = lambda: time.time() > now + 1
Затем я хочу, чтобы этот код продолжал зацикливаться (игнорировать комментарии, которые они на португальском языке) (также да, я знаю, что мой код не самый лучший, я только учусь):
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)
moderator = getModerator(line)
if channel == None or user == None or message == None:
break
#---------------------------------------------------------------------------------------------------------------------------------------------
#Formata o texto e mostra mostra na consola.--------------------------------------------------------------------------------------------------
print channel + ": " + user + " > " + message
#---------------------------------------------------------------------------------------------------------------------------------------------
###Essenciais END###----------------------------------------------------------------------------------------------------------------------------------------
if message == "!commands\r":
globalcommandskeys = str(globalcommands.keys()).replace("[", "").replace("]", "")
moderatorcommandskeys = str(moderatorcommands.keys()).replace("[", "").replace("]", "")
channelcommandskeys = str(commands.keys()).replace("[", "").replace("]", "")
sendMessage(irc, "Global commands: " + globalcommandskeys)
if channelcommandskeys != "":
sendMessage(irc, "Channel specific commands: " + channelcommandskeys )
if moderator == "1":
sendMessage(irc, "Moderator commands: " + moderatorcommandskeys)
break
if message.startswith("!addcom ") and (moderator == "1" or user == channel):
if message.count(" ") >= 2:
try:
commandadd = command_add(message)
answer = command_answer(message)
except IndexError:
sendMessage(irc, user + " the command is used this way !addcom !<command_name> <command_answer>")
break
if globalcommands.has_key(commandadd) or moderatorcommands.has_key(commandadd):
sendMessage(irc, user + " you can't add the command " + '"!' + commandadd + '" !!!')
break
try:
commands[commandadd]
except KeyError:
commands[commandadd] = answer
sendMessage(irc, user + " the command !" + commandadd + " has been added!!!")
with file("commands.json","w") as commandsDatabase:
json.dump(commands, commandsDatabase)
break
sendMessage(irc, user + " the command you tried to add alredy exists!!!")
break
sendMessage(irc, user + " the command is used this way !addcom !<command_name> <command_answer>")
break
if message.startswith("!delcom ") and (moderator == "1" or user == channel):
if message.count(" ") == 1:
try:
commanddel = command_del(message)
except IndexError:
sendMessage(irc, user + "the command is used this way !delcom !<command_name>")
break
if globalcommands.has_key(commanddel) or moderatorcommands.has_key(commanddel):
sendMessage(irc, user + " you can't delete the command " + '"!' + commanddel + '" !!!')
break
try:
commands[commanddel]
except KeyError:
sendMessage(irc, user + " the command you tried to delete doens't exist!!!")
break
del commands[commanddel]
sendMessage(irc, user + " the command !" + commanddel + " has been deleted!!!")
with file("commands.json","w") as commandsDatabase:
json.dump(commands, commandsDatabase)
break
sendMessage(irc, user + " the command is used this way !delcom !<command_name>")
break
if message.startswith("!"):
if cooldown() == True:
if message.count(" ") == 0:
try:
command = getCommand(message)
except IndexError:
break
try:
sendMessage(irc, commands[command])
now = time.time()
cooldown = lambda: time.time() > now + 10
except KeyError:
break
if message.count(" ") == 1:
try:
command = getCommandSpaced(message)
target = getString(message)
except IndexError:
break
try:
replacing = commands[command]
sendMessage(irc, replacing.replace("$target", target))
now = time.time()
cooldown = lambda: time.time() > now + 10
except KeyError:
break
break
И наконец, когда кнопка нажата «вверх», я хочу закрыть сокет, чтобы бот покинул irc-сервер:
irc.close()
Я хочу, чтобы все вышеперечисленное можно было сделать без закрытия и повторного открытия скрипта.
Так что проблема в том, что я не могу этого сделать.
Если я вставлю в основной скрипт (тот, который соединяет сигналы кнопок с графическим интерфейсом), он сломает основной цикл gtk, и графический интерфейс выйдет из строя.
Я пытался использовать потоки, но я, кажется, не понимаю их.